Releases
Forcodeexamples,seeEXAMPLES.mdadshare/doc/moderish/examplesmoderish–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:BudligmoderishwithyourscriptGettigstartedRuistall.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),seeAppedixFuistall.sh[-][-f][-distallroot]
-:o-iteractiveoperatio-f:delete*/moderishdirectorieseveiffilesleft-d:specifyrootdirectoryofmoderishistallatiotouistallTwobasicformsofamoderishprogramIthesimpleform,moderishisaddedtoascriptwritteforaspecificshell.Itheportableform,yourscriptisshell-agosticadmayruoayshellthatcarumoderish.
SimpleformThesimplestwaytowriteamoderishprogramistosourcemoderishasadotscript.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.)
PortableformThemostportablewaytowriteamoderishprogramistousethespecialgeerichashbagpathformoderishprograms.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.
IteractiveuseModerishisprimarilydesigedtoehaceshellprograms/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-iteractivecommadlieuseAfteristallatio,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.shShellcapabilitydetectioModerishicludesabatteryofshellfeature,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.
NamesadidetifiersAllmoderishfuctiosrequireportablevariableadshellfuctioames,thatis,oescosistigofASCIIuppercaseadlowercaseletters,digits,adtheuderscorecharacter_,adthatdo'tbegiwithdigit.Forshelloptioames,thecostraitsarethesameexceptadash-isalsoaccepted.Aivalididetifierisgeerallytreatedasafatalerror.
IteralamespaceFuctio-localvariablesareotsupportedbythestadardPOSIXshell;olyglobalvariablesareprovidedfor.Moderisheedsawaytostoreitsiteralstatewithoutiterferigwiththeprogramusigit.Somostofthemoderishfuctioalityusesaiteralamespace_Msh_*forvariables,fuctiosadaliases.Alltheseamesmaychageataytimewithoutotice.Ayamesstartigwith_Msh_shouldbecosideredsacrosactadutouchable;moderishprogramsshouldeverdirectlyusethemiayway.Ofcoursethisisoteforceable,butamesstartigwith_Msh_shouldbeucommoeoughthatouitetioalcoflictislikelytooccur.
ModerishsystemcostatsModerishprovidescertaicostats(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-safecharactercostatsPOSIXdoesotprovideforthequotedC-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"DONEReliableemergecyhaltThediefuctioreliablyhaltsprogramexecutio,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-levelshellutilitiesOutputtigstrigsThePOSIXshelllacksasimple,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,foreverModerishsetsthreealiasesthatcahelptomaketheshelllaguagelookslightlyfriedlier.Theiruseisoptioal.
otisaewsyoymfor!.Theycabeusediterchageably.
soisacommadthattestsifthepreviouscommadexitedwithastatusofzero,soyoucatesttheprecedigcommad'ssuccesswithifsoorifotso.
foreverisaewsyoymforwhile:;.Thisallowssimpleifiiteloopsoftheform:foreverdostuff;doe.
EhacedexitTheexitcommadcabeusedasormal,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.chdirchdirisarobustcdreplacemetforuseiscripts.
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.
isubshellTheisubshellfuctiochecksifyou'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.issetissetchecksifavariable,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).
setstatussetstatusmauallysetstheexitstatus$?tothedesiredvalue.Thefuctioexitswiththestatusidicated.Thisisusefulicoditioalcostructsifyouwattoprepareaparticularexitstatusforasubsequetexitorreturcommadtoiheritudercertaicircumstaces.Thestatusargumetisaparsedasashellarithmeticexpressio.Aegativevalueistreatedasafatalerror.Thebehaviourofvaluesgreatertha255isotstadardisedaddepedsoyourparticularshell.
Testigumbers,strigsadfilesThetest/[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:
评论