rc.byron(1)

shell

Section 1 rc bookworm source

Description

RC

NAME

rc - shell

SYNOPSIS

rc [-deiIlnopsvx] [-c command] [arguments]

DESCRIPTION

rc is a command interpreter and programming language similar to sh(1). It is based on the AT&T Plan 9 shell of the same name. The shell offers a C-like syntax (much more so than the C shell), and a powerful mechanism for manipulating variables. It is reasonably small and reasonably fast, especially when compared to contemporary shells. Its use is intended to be interactive, but the language lends itself well to scripts.

OPTIONS

-c 0

If-c0ispresent, commands are executed from the immediately following argument.Anyfurtherargumentstorcareplacedin$*.0Thus:

rc-c'echo$*'1230

printsout

1230

-d0

This flagcausesrcnottoignoreSIGQUIT0orSIGTERM.0Thusrccanbemadetodump coreifsentSIGQUIT.0Thisflagisonlyusefulfordebuggingrc.

-e0

Ifthe-e0flagispresent,thenrcwillexitif any command fails (exits with non-zero status). However rc -e does not exit if aconditionalfails.A conditionalisthetestofanif()0command,thetestofawhile()0command,orthe lefthandsideofthe||0orthe&&0operator.

-i0

Ifthe-i0flagispresentoriftheinputtorcisfromaterminal(asdetermined by isatty(3)) then rc will be in interactive mode. That is,aprompt(from $prompt(1))0willbeprintedbeforeaninputlineistaken,and rc will ignore SIGINT.0

-I0

If the-I0flagispresent,oriftheinputtorcisnotfromaterminal,thenrcwill notbeininteractivemode.Nopromptswillbeprinted,andSIGINT0willcause rc toexit.

-l0

If the -l0 flag is present,orifrc’sargv[0][0]0isadash(-),0thenrcwill behaveasaloginshell.Thatis,itwillruncommandsfrom$home/.rcrc,0if this fileexists,beforereadinganyotherinput.

-n0

Thisflagcausesrctoreaditsinputandparseit,butnottoexecuteanycommands. Thisisusefulforsyntaxcheckingonscripts.Ifusedincombinationwiththe-x0 flag,rcwillprinteachcommandasitisparsedinaformsimilartotheoneusedfor exportingfunctionsintotheenvironment.

-o0

This flag prevents the usual practice oftryingtoopen/dev/null0onfile descriptors0,1,and2,ifanyofthosedescriptorsareinheritedclosed.

-p0

Thisflagpreventsrcfrominitializingshellfunctionsfromthe environment. Thisallowsrctoruninaprotectedmode,wherebyitbecomesmoredifficultforan rc script to besubvertedbyplacingfalsecommandsintheenvironment.(Note thatthepresenceofthisflagdoesnotmeanthat it is safe to run setuid rc scripts;theusualcaveatsaboutthesetuidbitstillapply.)

-s0

Thisflagcausesrctoreadfromstandardinput.Anyargumentsareplacedin$*.0

-v0

Thisflagcausesrctoechoitsinputtostandarderrorasitisread.

-x0

This flag causes rc to print every command onstandarderrorbeforeitis executed.Itcanbeusefulfordebuggingrcscripts.

COMMANDS

Asimplecommandisasequenceof words, separated by white space (space and tab) charactersthatendswithanewline,semicolon(;),0orampersand(&).0Thefirstwordof acommandisthenameofthatcommand.Ifthenamebeginswith/,0./,0or../,0thenthename is used asanabsolutepathnamereferringtoanexecutablefile.Otherwise,thenameof thecommandislookedupinatableofshellfunctions,builtincommands,orasafileinthe directoriesnamedby$path.0

BackgroundTasks

Acommandendingwith&0isruninthebackground;thatis,theshellreturns immediately rather than waitingforthecommandtocomplete.Backgroundcommandshave/dev/null0 connectedtotheirstandardinputunlessanexplicitredirectionforstandardinput is used.

Subshells

A command prefixed with anat-sign(@)0isexecutedinasubshell.Thisinsulatesthe parentshellfromtheeffectsofstatechangingoperationssuchas a cd or a variable assignment.Forexample:

@{cd..;make}0

will run make(1) in the parent directory(..),0butleavestheshellrunninginthe currentdirectory.

Linecontinuation

Alonglogicallinemaybecontinuedoverseveralphysicallinesbyterminatingeachline (exceptthelast)withabackslash(\).0Thebackslash-newlinesequenceistreatedas a space. A backslash is not otherwise special to rc.(Inaddition,insidequotesa backslashlosesitsspecialmeaningevenwhenitisfollowedbyanewline.)

Quoting

rcinterprets several characters specially; special characters automatically terminatewords.Thefollowingcharactersarespecial:

#;&|ˆ$`’{}()<>0

Thesinglequote(’)0preventsspecialtreatmentofanycharacterotherthanitself.All characters, including control characters, newlines,andbackslashesbetweentwo quotecharactersaretreatedasanuninterpretedstring.Aquotecharacteritselfmaybe quotedbyplacingtwoquotesinarow.Theminimalsequence needed to enter the quote characteris’’’’.0Theemptystringisrepresentedby’’.0Thus:

echo’What’’stheplan,Stan?’0

printsout

What’stheplan,Stan?0

Thenumbersign(#)0beginsacommentinrc.Allcharactersuptobutnotincludingthenext newline are ignored.Notethatbackslashcontinuationdoesnotworkinsideacomment, i.e.,thebackslashisignoredalongwitheverythingelse.

Grouping

Zeroormorecommandsmaybegroupedwithinbraces(“{”0and“}”),0andarethentreatedas onecommand.Bracesdonototherwisedefine scope; they are used only for command grouping.Inparticular,bewaryofthecommand:

for(i){0
command0
}|command0

Sincepipebindstighterthanfor,0thiscommanddoesnotperformwhattheuserexpectsit to.Instead,enclosethewholefor0statementinbraces:

{for(i)command}|command0

Fortunately, rc’sgrammarissimpleenoughthata(confident)usercanunderstanditby examiningtheskeletalyacc(1)grammarattheendof this man page (see the section entitledGRAMMAR).

Inputandoutput

Thestandardoutputmayberedirectedtoafilewith

command>file0

andthestandardinputmaybetakenfromafilewith

command<file0

Redirectionscanappearanywhereintheline:thewordfollowingtheredirectionsymbol is the filename and mustbequotedifitcontainsspacesorotherspecialcharacters. Theseareallequivalent.

echo123>foo0
>fooecho1230
echo12>foo30

Filedescriptorsotherthan0and1maybe specified also. For example, to redirect standarderrortoafile,use:

command>[2]file0

In order to duplicate afiledescriptor,use>[n=m].0Thustoredirectbothstandard outputandstandarderrortothesamefile,use

command>file>[2=1]0

Asinsh,redirectionsareprocessedfromlefttoright.Thusthissequence

command>[2=1]>file0

isusuallyamistake.Itfirstduplicates standard error to standard output; then redirects standard outputtoafile,leavingstandarderrorwhereverstandardoutput originallywas.

Tocloseafiledescriptorthatmaybeopen, use >[n=].0 For example, to close file descriptor7:

command>[7=]0

Notethatnospacesmayappearintheseconstructs:

command>[2]file0

would send the output of thecommandtoafilenamed[2],0withtheintendedfilename appearinginthecommand’sargumentlist.

Inordertoplacetheoutputofacommandattheendofanalreadyexistingfile,use:

command>>file0

Ifthefiledoesnotexist,thenitiscreated.

“Heredocuments”aresupportedasinshwiththeuseof

command<<'eof-marker'0

Subsequentlinesformthestandardinputofthecommand,tillalinecontainingjust the marker,inthiscaseeof-marker,0isencountered.

If the end-of-filemarkerisenclosedinquotes,thennovariablesubstitutionoccurs inside the here document. Otherwise, every variable is substituted by its space-separated-list value (see Flat Lists,below),andifaˆ0characterfollowsa variablename,itisdeleted.Thisallowstheunambiguoususeofvariables adjacent to text,asin

$variableˆfollow0

To include a literal$0inaheredocumentwhenanunquotedend-of-filemarkerisbeing used,enteritas$$.0

Additionally,rcsupports“herestrings”,whicharelikeheredocuments, except that inputistakendirectlyfromastringonthecommandline.Theiruseisillustratedhere:

cat<<<'thisisaherestring'|wc0

(Thisfeatureenablesrctoexportfunctionsusingheredocumentsintotheenvironment; theauthordoesnotexpectuserstofindthisfeatureuseful.)

Pipes

Twoormorecommandsmaybecombinedinapipelinebyplacingtheverticalbar(|)0between them. The standard output (filedescriptor1)ofthecommandontheleftistiedtothe standardinput(filedescriptor0)ofthecommandonthe right. The notation |[n=m]0 indicates thatfiledescriptornoftheleftprocessisconnectedtofiledescriptormof therightprocess.|[n]0isashorthandfor|[n=0].0Asanexample,topipe the standard errorofacommandtowc(1),use:

command|[2]wc0

Aswithfileredirections,nospacesmayoccurintheconstructspecifyingnumberedfile descriptors.

The exit status of a pipeline is consideredtrueifandonlyifeverycommandinthe pipelineexitstrue.

CommandsasArguments

Somecommands,likecmp(1)ordiff(1),taketheirargumentsonthecommandline, and do not read input from standard input. Itisconvenientsometimestobuildnonlinear pipelinessothatacommandlikecmpcanreadtheoutputoftwoothercommandsat once. rc doesitlikethis:

cmp<{command}<{command}0

comparestheoutputofthetwocommandsinbraces.Note:sincethisformofredirectionis implementedwithsomekindofpipe,andsinceonecannotlseek(2)onapipe,commandsthat use lseek(2) will hang. For example,someversionsofdiff(1)uselseek(2)ontheir inputs.

Datacanbesentdownapipetoseveralcommandsusingtee(1)andtheoutputversionofthis notation:

echohithere|tee>{sed's/ˆ/p1/'}>{sed's/ˆ/p2/'}0

CONTROLSTRUCTURES

Thefollowingmaybeusedforcontrolflowinrc:

If-ElseStatements

if(test){0
cmd

}elsecmd0

Thetestisexecuted,andifitsreturnstatus is zero, the first command is executed, otherwise the second is. Braces are not mandatoryaroundthe commands.However,anelse0statementisvalidonlyifitfollowsa close-brace onthesameline.Otherwise,theif0istakentobeasimple-if:

if(test)0
command0

WhileandForLoops

while(test)cmd0

rcexecutesthetestandperformsthecommandaslongasthetestistrue.

for(varinlist)cmd0

rc sets var toeachelementoflist(whichmaycontainvariablesandbackquote substitutions)andrunscmd.If“in0list”isomitted,thenrcwillsetvartoeach elementof$*.0Forexample:

for(iin`{ls-F|grep'\*$'|sed's/\*$//'}){commands}0

willset$i0tothenameofeachfileinthecurrentdirectorythatisexecutable.

Switch

switch(list){case...}0

rclooksinsidethebracesafteraswitch0forstatementsbeginningwiththeword case.0Ifanyofthepatternsfollowingcase0matchthelistsuppliedtoswitch,0 thenthe commands up until the next case0 statement are executed. The metacharacters *,0 [0 or ?0shouldnotbequoted;matchingisperformedonly againstthestringsin list, not against file names. (Matching for case statementsisthesameasforthe˜0command.)

LogicalOperators

Thereareanumberofoperatorsinrcwhichdependontheexitstatusofacommand.

command&&command0

executes the firstcommandandthenexecutesthesecondcommandifandonlyifthefirst commandexitswithazeroexitstatus(“true”inUnix).

command||command0

executesthefirstcommandandthenexecutesthesecondcommandifandonlyif the first commandexitswithanonzeroexitstatus(“false”inUnix).

!command0

negatestheexitstatusofacommand.

PATTERNMATCHING

There are two formsofpatternmatchinginrc.Oneistraditionalshellglobbing.This occursinmatchingforfilenamesinargumentlists:

commandargumentargument...0

Whenthecharacters*,0[0or?0occurinanargumentorcommand,rclooksattheargumentas apatternformatchingagainstfiles.(Contrarytothebehaviorothershellsexhibit,rc willonlyperformpatternmatchingifametacharacteroccursunquotedandliterally in theinput.Thus,

foo='*'0
echo$foo0

will alwaysechojustastar.Inorderfornon-literalmetacharacterstobeexpanded,an eval0statementmustbeusedinordertorescan the input.) Pattern matching occurs according to the following rules: a *0 matches any number (includingzero)of characters.A?0matchesanysinglecharacter,anda[0followedbyanumberofcharacters followedbya]0matchesasinglecharacterinthatclass.Therulesfor character class matching are the same as those for ed(1),withtheexceptionthatcharacterclass negationisachievedwiththetilde(˜),0notthecaret(ˆ),0 since the caret already meanssomethingelseinrc.

rcalsomatchespatternsagainststringswiththe˜0command:

˜subjectpatternpattern...0

The˜0commandsucceeds(sets$status0tozero)ifandonlyifoneofthepatterns0matches subject.0Thus

˜foof*0

succeeds(setsstatustozero),while

˜barf*0

fails(setsstatustoone).

Thenulllistismatchedbythenulllist,so

˜$foo()0

checks toseewhether$foo0isemptyornot.Becausercdoesnothavehierarchicallists, thetestforemptinesscannotbecombinedwithothertests. To test whether $foo0 is empty,oroneofthestringsnada0orrien,0donotwrite

˜$x()nadarien#WRONGmeansthesameas:˜$xnadarien0

insteadwrite

˜$x()||˜$xnadarien0

Anotherwaytotestif$foo0isemptyis

˜$#foo00

Note that inside a˜0commandrcdoesnotmatchpatternsagainstfilenames,soitisnot necessarytoquotethecharacters*,0[0and?.0However, rc does expand the subject againstfilenamesifitcontainsmetacharacters.Thus,thecommand

˜*?0

succeedsifanyofthefilesinthecurrentdirectoryhaveasingle-charactername.

Ifthe˜0commandisgivenalistasitsfirstargument,thenasuccessfulmatchagainstany oftheelementsofthatlistwillcause˜0tosucceed.Forexample:

˜(foogoozoo)z*0

istrue.

LISTSANDVARIABLES

Theprimarydatastructureinrcisthelist,whichisasequenceofwords.Parenthesesare used to group lists. Theemptylistisrepresentedby().0Listshavenohierarchical structure;alistinsideanotherlistisexpandedsothe outer list contains all the elementsoftheinnerlist.Thus,thefollowingareallequivalent

onetwothree0

(onetwothree)0

((one)()((twothree)))0

Note that the null string,'',0andthenulllist,(),0aretwoverydifferentthings. Assigningthenullstringtoavariableisavalidoperation,butitdoes not remove its definition.

null=''empty=()echo$#null$#empty0

producestheoutput

100

ListConcatenation

Two lists may be joined by the concatenationoperator(ˆ).0Concatenationworks accordingtothefollowingrules:ifthetwolistshavethesamenumberofelements, then concatenationispairwise:

echo(a-b-c-)ˆ(123)0

producestheoutput

a-1b-2c-30

Otherwise, at least one of the lists must have a single element, andthenthe concatenationisdistributive:

cc-ˆ(Ogc)(mallocalloca)ˆ.c0

hastheeffectofperformingthecommand

cc-O-g-cmalloc.calloca.c0

Asinglewordisalistoflengthone,so

echofooˆbar0

producestheoutput

foobar0

FreeCarets

rcinsertscarets(concatenationoperators)forfreeincertainsituations,inorderto savesometypingontheuser’sbehalf.Forexample,theaboveexamplecouldalsobe typed inas:

opts=(Ogc)files=(mallocalloca)cc-$opts$files.c0

rc takes care to insert afreecaretbetweenthe‘‘-’’0and$opts,0aswellasbetween $files0and.c.0Theruleforfreecaretsisasfollows:ifawordorkeywordisimmediately followedbyanotherword,keyword,dollar-signorbackquote,thenrc inserts a caret betweenthem.

Variables

Alistmaybeassignedtoavariable,usingthenotation:

var=list0

Thespecialvariable*0mayalsobeassignedtousingthisnotation;rchasnosetbuiltin.

Any non-empty sequenceofcharacters,exceptasequenceincludingonlydigits,maybe usedasavariablename.Anycharacterexcept=0maybeused,butspecialcharacters must bequoted.Alluser-definedvariablesareexportedintotheenvironment.

Thevalueofavariableisreferencedwiththedollar($)0operator:

$var0

Any variable which has not been assigned a valuereturnsthenulllist,(),0when referenced.Multiplereferencesareallowed:

a=foo0
b=a0
echo$$b0

prints

foo0

Avariable’sdefinitionmayalsoberemovedbyassigningthenulllisttoavariable:

var=()0

For“freecareting”toworkcorrectly,rcmust make certain assumptions about what charactersmayappearinavariablename.rcassumesthatavariablenameconsistsonlyof alphanumeric characters, underscore(_)0andstar(*).0Toreferenceavariablewith othercharactersinitsname,quotethevariablename.Thus:

echo$'we$Ird:Variab!le'0

LocalVariables

Anynumberofvariableassignmentsmaybemadelocaltoasinglecommandbytyping:

a=foob=bar...command0

Thecommandmaybeacompoundcommand,soforexample:

path=.ifs=(){0
...0
}0

setspath0to.0andremovesifs0forthedurationofonelongcompoundcommand.

VariableSubscripts

Variablesmaybesubscriptedwiththenotation

$var(n)0

wherenisalistofintegers(origin1).Theopeningparenthesismustimmediatelyfollow thevariablename.Thelistofsubscriptsneednotbeinorderorevenunique.Thus,

a=(onetwothree)0
echo$a(333)0

prints

threethreethree0

Ifnreferencesanonexistentelement,then$var(n)0returnsthenulllist.Thenotation $n,0wherenisaninteger,isashorthandfor$*(n).0Thus,rc’sargumentsmaybereferred toas$1,0$2,0andsoon.

Notealsothatthelistofsubscriptsmaybegivenbyanyofrc’slistoperations:

$var(`{awk'BEGIN{for(i=1;i<=10;i++)printi;exit;}'})0

returnsthefirst10elementsof$var.0

Tocountthenumberofelementsinavariable,use

$#var0

Thisreturnsasingle-elementlist,withthenumberofelementsin$var.0

FlatLists

Inordertocreateasingle-elementlistfromamulti-elementlist,withthe components space-separated,usethedollar-caret($ˆ)0operator:

$ˆvar0

Thisisusefulwhenthenormallistconcatenationrulesneedtobebypassed.Forexample, toappendasingleperiodattheendof$path,0use:

echo$ˆpath.0

ForcompatibilitywiththePlan9rc,

$"var0

isacceptedasasynonymfordollar-caret.

BackquoteSubstitution

Alistmaybeformedfromtheoutputofacommandbyusingbackquotesubstitution:

`{command}0

returns a listformedfromthestandardoutputofthecommandinbraces.$ifs0isusedto splittheoutputintolistelements.Bydefault,$ifs0hasthevaluespace-tab-newline.

Thebracesmaybeomittedifthecommandisasingleword.Thus`ls0maybeused instead of `{ls}.0 This last feature canbeusedtocreateshortcutsbydefiningfunctionsthat expandtousefulargumentlists.Forexample:

fnsrc{echo*.[chy]}0

followedby

wc`src0

Thiswillprintoutaword-countofallCsourcefilesinthecurrentdirectory.

Inordertooverridethevalueof$ifs0forasinglebackquotesubstitution,use:

``(ifs-list){command}0

$ifs0willbetemporarilyignoredandthecommand’soutputwillbesplitasspecified by thelistfollowingthedoublebackquote.Forexample:

``($nl:){cat/etc/passwd}0

splitsup/etc/passwd0intofields.

As aconvenience,rcdefines$nl0tocontainthenewlinecharacter,and$tab0tocontain thetabcharacter.Thus,ifyouwanttoprocesseverythinginthecurrentdirectory, but inarandomorder,youcoulduse:

for(fin``$nl{ls|shuf}){...process$f}0

Thiswillcorrectlyhandlefilenamesthatcontainspaces.

Notethatrcscriptsthatusebackquotesubstitutionshouldavoidrelyingonthedefault valuesof$ifs,0$nl,0or$tab.0Instead,theyshouldexplicitlysetwhattheyneed.

SPECIALVARIABLES

Several variables are known to rcandaretreatedspecially.Inthefollowinglist, “default”indicatesthatrcgivesthevariableadefaultvalueonstartup; “no-export” indicates that the variable is never exported;and“read-only”indicatesthatan attempttosetthevariablewillsilentlyhavenoeffect.

Also,“alias”meansthatthevariableisaliased to the same name in capitals. For example, an assignment to $cdpath0causesanautomaticassignmentto$CDPATH,0and vice-versa.If$CDPATH0issetwhenrcisstarted,itsvalueisimported into $cdpath.0 $cdpath0 and $path0arerclists;$CDPATH0and$PATH0arecolon-separatedlists.Only thenamesspeltincapitalsareexportedintotheenvironment.
*(no-export)0

Theargumentlistofrc.$1,$2,0etc.arethesameas$*(1),0$*(2),0etc.

0(defaultno-export)0

Thevariable$00holds the value of argv[0]0 with which rc was invoked. Additionally, $00 is set to the name of afunctionforthedurationofthe executionofthatfunction,and$00isalsosetto the name of the file being interpreted for thedurationofa.0command.$00isnotanelementof$*,0andis nevertreatedasone.

apid(no-export)0

TheprocessIDofthelastprocessstartedinthebackground.

apids(no-exportread-only)0

AlistwhoseelementsaretheprocessIDsofallbackgroundprocesses which are stillalive,orwhichhavediedandhavenotbeenwaitedforyet.

bqstatus(no-export)0

The exit status of the rc forked to execute the most recentbackquote substitution.Notethat,unlike $status,0 $bqstatus0 is always a single elementlist(seeEXITSTATUSbelow).Forexample:

echofoo|grepbar;whatisstatus0

prints

status=(01)0

whereas

x=`{echofoo|grepbar};whatisbqstatus0

prints

bqstatus=10

cdpath(alias)0

A list of directoriestosearchforthetargetofacdcommand.Theemptystring standsforthecurrentdirectory.Notethatifthe$cdpath0 variable does not containthecurrentdirectory,thenthecurrentdirectorywillnotbesearched; this allows directorysearchingtobegininadirectoryotherthanthecurrent directory.

history0

$history0containsthenameofafiletowhichcommandsareappendedas rc reads them. This facilitates the use of a stand-alonehistoryprogram(suchas history(1))whichparsesthecontentsofthehistoryfileandpresentsthemtorc forreinterpretation.If$history0isnotset,thenrcdoesnotappend commands toanyfile.

home(alias)0

The default directoryforthebuiltincdcommand,andthedirectoryinwhichrc lookstofinditsinitializationfile,.rcrc,0ifrchasbeenstartedupasalogin shell.

ifs(default)0

Theinternalfieldseparator,usedforsplittingup the output of backquote commands fordigestionasalist.Onstartup,rcassignsthelistcontainingthe charactersspace,tab,andnewlineto$ifs.0

nl(default)0

Containsthenewlinecharacter(seeBackquotesubstitutionabove).

path(alias)0

Thisisalistofdirectoriestosearchinforcommands.Theempty string stands for the currentdirectory.Ifneither$PATH0nor$path0issetatstartuptime, $path0assumesadefaultvaluesuitablefor your system. This is typically (/usr/local/bin/usr/bin/usr/ucb/bin.)0

pid(defaultno-export)0

On startup, $pid0 is initialized tothenumericprocessIDofthecurrently runningrc.

prompt(default)0

Thisvariableholdsthetwoprompts(inlistform,of course) that rc prints. $prompt(1)0 isprintedbeforeeachcommandisread,and$prompt(2)0isprinted wheninputisexpectedtocontinueonthenextline.rcsets$prompt0to(';' '')0 by default.Thereasonforthisisthatitenablesanrcusertograbcommandsfrom previouslinesusingamouse,andtopresentthemtorc for re-interpretation; the semicolon promptissimplyignoredbyrc.Thenull$prompt(2)0alsohasits justification:an rc script, when typed interactively, will not leave $prompt(2)’s0 on thescreen,andcanthereforebegrabbedbyamouseandplaced directlyintoafileforuseasashellscript, without further editing being necessary.

prompt(function)0

If thisfunctionisdefined,thenitgetsexecutedeverytimercisabouttoprint $prompt(1).0

status(no-exportread-only)0

Theexitstatusofthelastcommand.Ifthecommandexitedwitha numeric value, thatnumberisthestatus.Ifthecommanddiedwithasignal,thestatusisthename of that signal;ifacorefilewascreated,thestring“+core”0isappended.The valueof$status0forapipelineisalist,withone entry, as above, for each processinthepipeline.Forexample,thecommand

ls|wc0

usuallysets$status0to(00).0

tab(default)0

Containsthetabcharacter(seeBackquotesubstitutionabove).

version(default)0

On startup, the firstelementofthislistvariableisinitializedtoastring whichidentifiesthisversionofrc.Thesecond element is initialized to a stringwhichcanbefoundbyident(1)andthewhatcommandofsccs(1).

FUNCTIONS

rc functions are identicaltorcscripts,exceptthattheyarestoredinmemoryandare automaticallyexportedintotheenvironment.Ashellfunctionisdeclaredas:

fnname{commands}0

rcscansthedefinitionuntiltheclose-brace,sothefunctioncan span more than one line.Thefunctiondefinitionmayberemovedbytyping

fnname0

(One ormorenamesmaybespecified.Withanaccompanyingdefinition,allnamesreceive thesamedefinition.Thisissometimesusefulforassigningthesamesignal handler to manysignals.Withoutadefinition,allnamedfunctionsaredeleted.)Whenafunctionis executed, $*0 is settotheargumentstothatfunctionforthedurationofthecommand. Thusareasonabledefinitionforl,0ashorthandforls(1),couldbe:

fnl{ls-FC$*}0

butnot

fnl{ls-FC}#WRONG0

INTERRUPTSANDSIGNALS

rcrecognizesanumberofsignals,andallowstheusertodefineshellfunctionswhichact assignalhandlers.rcbydefaulttrapsSIGINT0whenitisininteractivemode. SIGQUIT0 and SIGTERM0 are ignored, unless rc has been invokedwiththe-d0flag.However, user-definedsignalhandlersmaybewrittenfortheseandallothersignals.The way to defineasignalhandleristowriteafunctionbythenameofthesignalinlowercase.Thus:

fnsighup{echohangup;rm/tmp/rc$pid.*;exit}0

In additiontoUnixsignals,rcrecognizestheartificialsignalSIGEXIT0whichoccurs asrcisabouttoexit.

Inordertoremoveasignalhandler’sdefinition,removeitasthoughit were a regular function.Forexample:

fnsigint0

returns the handlerofSIGINT0tothedefaultvalue.Inordertoignoreasignal,setthe signalhandler’svalueto{}.0Thus:

fnsigint{}0

causesSIGINT0tobeignoredbytheshell.Onlysignalsthatarebeingignoredare passed ontoprogramsrunbyrc;signalfunctionsarenotexported.

OnSystemV-basedUnixsystems,rcwillnotallowyoutotrapSIGCLD.0

BUILTINCOMMANDS

Builtin commandsexecuteinthecontextoftheshell,butotherwisebehaveexactlylike othercommands.Although!,˜and@arenotstrictlyspeakingbuiltincommands,they can usuallybeusedassuch.
.
[-i]file[arg...]

Reads file as input to rcandexecutesitscontents.Witha-i0flag,inputis interactive.Thusfromwithinashellscript,

.-i/dev/tty0

doesthe“rightthing”.

break

Breaksfromtheinnermostfor0orwhile,0asinC.Itisanerror to invoke break outside of a loop. (Note that thereisnobreakkeywordbetweencommandsin switch0statements,unlikeC.)

builtincommand[arg...]

Executesthecommandignoringanyfunctiondefinitionofthe same name. This command is presenttoallowfunctionswiththesamenamesasbuiltinstousethe underlyingbuiltinorbinary.Forexample:

fnls{builtinls-FC$*}0

isareasonablewaytopassadefaultsetofargumentstols(1),0whereas

fnls{ls-FC$*}#WRONG0

isanon-terminatingrecursion,whichwillcauserc0toexhaustitsstack space and(eventually)terminateifitisexecuted.

cd[directory]

Changes thecurrentdirectorytodirectory.Thevariable$cdpath0issearched forpossiblelocationsofdirectory,analogoustothesearchingof $path0 for executablefiles.Withnoargument,cdchangesthecurrentdirectoryto$home.0

continue

Continues the innermost for0 or while0loop,asinC.Itisanerrortoinvoke continueoutsideofaloop.

echo[-n][--][arg...]

Printsitsargumentstostandardoutput,terminatedbyanewline.Argumentsare separatedbyspaces.Ifthefirstargumentis-n0nofinalnewlineisprinted. If thefirstargumentis--,0thenallotherargumentsareechoedliterally.Thisis usedforechoingaliteral-n.0

eval[list]

Concatenates theelementsoflistwithspacesandfeedstheresultingstringto rcforre-scanning.Thisistheonlytimeinputisrescannedinrc.

exec[arg...]

Replacesrcwiththegivencommand.Iftheexeccontainsonlyredirections,then theseredirectionsapplytothecurrentshellandtheshelldoes not exit. For example,

exec>[2]err.out0

placesfurtheroutputtostandarderrorinthefileerr.out.

exit[status]

Cause the current shell to exitwiththegivenexitstatus.Ifnoargumentis given,thecurrentvalueof$status0isused.

flagf[+|-]

Test,set(+),orreset(-)command-lineflag f. For example, a script that requires‘‘exitifcommandfails’’semanticscansay

flage+0

Some flags cannotbesetorresetusingflag,buttheycanstillbetested.These arec,d,l,o,p,ands.Asaspecial case, flag i0 operates on rc’s internal interactive flag, which may have been set by-i0onthecommandline,orif standardinputwasaterminal;thereisnoflagI.0

limit[-h][resource[value]]

Similartothecsh(1)limitbuiltin,thiscommandoperatesupon the BSD-style resource limitsofaprocess.The-h0flagdisplays/altersthehardlimits.The resourceswhichcanbeshown or altered are cputime, filesize, datasize, stacksize, coredumpsize, memoryuse, and, wheresupported,descriptors, memoryuse,memoryrss,maxproc,memorylocked,andfilelocks.Forexample:

limitcoredumpsize00

disablescoredumps.Tosetasoftlimitequaltothehardlimit:

limit`{limit-hdatasize}0

newpgrp

Putsrcintoanewprocessgroup.Thisbuiltinisusefulformakingrcbehavelikea job-controlshellinahostileenvironment.Oneexampleis the NeXT Terminal program,whichimplicitlyassumesthateachshellitforkswillputitselfintoa newprocessgroup.

return[n]

Returns fromthecurrentfunction,withstatusn,wherenisavalidexitstatus, oralistofthem.Thusitislegaltohave

return(sigpipe123)0

(Thisiscommonlyusedtoallowafunctiontoreturnwith the exit status of a previously executed pipeline ofcommands.)Ifnisomitted,then$status0is leftunchanged.Itisanerrortoinvokereturnwhennotinsideafunction.

shift[n]

Deletesnelementsfromthebeginningof$*0andshiftstheotherelementsdownby n.ndefaultsto1.

umask[mask]

Setsthecurrentumask(seeumask(2))to the octal mask. If no argument is present,thecurrentmaskvalueisprinted.

wait[pid]

Waits for processwiththespecifiedpid,whichmusthavebeenstartedbyrc,to exit.Ifnopidisspecified,rcwaitsforallitschildprocessestoexit.

whatis[-b][-f][-p][-s][-v][--][name...]

Printsadefinitionofthenamedobjects.Forbuiltins,builtin0fooisprinted; forfunctions,includingsignalhandlers,theirdefinitionsareprinted; for executable files, pathnamesareprinted;andforvariables,theirvaluesare printed.The flags restrict output to builtins, functions, executable programs, signal handlers, and variables, respectively. Ifnonamesare specified,rclistsallobjectsofthattype.(Thisisnot permitted for -p.)0 Without arguments,whatis0isequivalenttowhatis-fv,0andprintsthevalues ofallshellvariablesandfunctions.

Notethatwhatisoutputissuitableforinputtorc;bysavingtheoutputofwhatis inafile,itshouldbepossibletorecreatethestateofrcbysourcing this file witha.0command.Anothernote:whatis-s>file0cannotbeusedtostorethestate ofrc’ssignalhandlersinafile,becausebuiltinswithredirectionsarerunina subshell, andrcalwaysrestoressignalhandlerstotheirdefaultvalueaftera fork().0

Sincewhatisusesgetopt(3)toparseitsarguments, you can use the special argument--0toterminateitsflags.Thisallowsyoutousenamesbeginningwitha dash,suchasthehistory(1)commands.Forexample,

whatis---p0

EXAMPLES

The shift builtin only shifts $*.0 This function canshiftanyvariable(except $_lshift).0

fnlshift{_lshift=$**=$$1{shift$_lshift(2);$_lshift(1)=$*}}0

Withthisdefinitioninplace,

walrus=(shoesshipssealing-waxcabbageskings)0
lshiftwalrus30
whatiswalrus0

prints

walrus=(cabbageskings)0

The$ˆvar0operatorflattensalistby separating each element with a space. This functionallowstheseparatortobeanarbitrarystring.

fnlflat{0
lflat=$*;*=$$10
while(){0
echo-n$1;shift0
˜$#*0&&break0
echo-n$lflat(2)0
}0
}0

Withthisdefinitioninplace,

hops=(uunetmcvaxukctlg)0
lflathops!0

prints(withnofinalnewline)

uunet!mcvax!ukc!tlg0

EXITSTATUS

The exitstatusofrcisnormallythesameasthatofthelastcommandexecuted.Ifthelast commandwasapipeline,rcexits00ifeverycommandinthe pipeline did; otherwise it exits1.0

rccanbemadetoexitwithaparticularstatususingtheexitbuiltin.

LINEEDITING

rc is typically built againstalineeditinglibrary.OnGNU/Linuxsystemsthiswill usuallybetheGNUreadlinelibrary.On*BSDsystemsit is more likely to be the BSD editlinelibrary.Pleaseconsulttheappropriatelibrarydocumentationfordetailsof howtouseandconfigurelineediting.

TildeExpansion

Sincercdoesnotsupporttildeexpansion(converting˜foo0tothehomedirectoryofuser foo),0 it is sometimes suggestedbyusersasapossibleenhancement.Theauthorsand maintainersofrchaveaproudhistoryofresistingsuchfeaturerequests.Soitis worth noting here that GNUreadlinecanexpandtildes.Addthislinetothefile.inputrc0in yourhomedirectory.

setexpand-tildeon0

andthenusethekeysequenceM-˜0toperformtildeexpansiononthecurrentword.See the readlinedocumentationforfurtherdetails.

GRAMMAR

Hereisrc’sgrammar,editedtoremovesemanticactions.

%termANDANDBACKBACKBANGCASECOUNTDUPELSEENDFLATFNFORIFIN
%termORORPIPEREDIRSUBSUBSHELLSWITCHTWIDDLEWHILEWORDHUH

%left’ˆ’’=’
%leftWHILE’)’ELSE
%leftANDANDOROR’\n’
%leftBANGSUBSHELL
%leftPIPE
%right’$’
%leftSUB

%startrc

%%

rc:lineend

|errorend

end:END/*EOF*/|’\n’

cmdsa:cmd’;’|cmd’&’

line:cmd|cmdsaline

body:cmd|cmdsanbody

cmdsan:cmdsa|cmd’\n’

brace:’{’body’}’

paren:’(’body’)’

assign:firstoptcaret’=’optcaretword

epilog:/*empty*/|redirepilog

redir:DUP|REDIRword

case:CASEwords’;’|CASEwords’\n’

cbody:cmd|casecbody|cmdsancbody

iftail:cmd

%precELSE

|braceELSEoptnlcmd

cmd

:/*empty*/

%precWHILE

|simple

|braceepilog

|IFparenoptnliftail

|FOR'('wordINwords')'optnlcmd

|FOR'('word')'optnlcmd

|WHILEparenoptnlcmd

|SWITCH'('word')'optnl'{'cbody'}'

|TWIDDLEoptcaretwordwords

|cmdANDANDoptnlcmd

|cmdORORoptnlcmd

|cmdPIPEoptnlcmd

|redircmd

%precBANG

|assigncmd

%precBANG

|BANGoptcaretcmd

|SUBSHELLoptcaretcmd

|FNwordsbrace

|FNwords

optcaret:/*empty*/%prec’ˆ’|’ˆ’

simple:first|firstargs

args:arg|argsarg

arg:word|redir

first:comword|first’ˆ’sword

sword:comword|keyword

word:sword|word’ˆ’sword

comword:’$’sword

|’$’swordSUBwords’)’

|COUNTsword

|FLATsword

|’‘’sword

|’‘’brace

|BACKBACKword

brace|BACKBACKwordsword

|’(’words’)’

|REDIRbrace

|WORD

keyword:FOR|IN|WHILE|IF|SWITCH

|FN|ELSE|CASE|TWIDDLE|BANG|SUBSHELL|’=’

words:/*empty*/|wordsword

optnl:/*empty*/|optnl'\n'

FILES

$HOME/.rcrc,0/tmp/rc*,0/dev/null0

CREDITS

rcwaswrittenbyByronRakitzis,withvaluablehelpfromPaulHaahr,HughRedelmeierand DavidSanderson.ThedesignofthisshellwascopiedfromthercthatTomDuffwroteatBell Labs.

BUGS

There is a compile-timelimitonthenumberof;0separatedcommandsinaline:usually 500.Thisissometimesaproblemforautomaticallygeneratedscripts:substitutingthe newlinecharacterfor;0avoidsthelimit.

Onmodernsystemsthatsupport/dev/fd0or/proc/self/fd,0<{foo}0style redirection is implemented thatway.However,onoldersystemsitisimplementedwithnamedpipes. Allegedly,itissometimespossibletofoilrcintoremovingtheFIFOitplaces in /tmp0 prematurely,oritisevenpossibletocauserctohang.(Thecurrentmaintainerhasnever seen this, but thenhedoesn’tusesystemswhichlack/dev/fd0anymore.Ifanybodycan reproducethisproblem,pleaseletthemaintainerknow.)

Theechocommanddoesnotneedtobeabuiltin.Itisonefor reasons of performance and portability(ofrcscripts).

Thereshouldbeawaytoavoidexportingavariable.

Extraparenthesesarounda˜0expressionora!0expressionareasyntaxerror.Thus,this codeisillegal.

while((˜$1-*)&&(!˜$1--)){...0

Theredundantinnerparenthesesmustbeomitted.

Variablesubscriptingcannotbeusedinheredocuments.

Thelimit0builtinsilentlyignoresextraarguments.

Backquote substitution never produces empty strings - multiple consecutive occurrencesoftheseparatoraretreatedthesameasasingleoccurrence.

ifs=!{x=`{echo-na!!b};whatisx}0
x=(ab)#NOTx=(a''b)0

Bugreportsshouldbemailedto
<toby@paccrat.org>.0

INCOMPATIBILITIES

Hereisalistoffeatureswhichdistinguishthisincarnationofrcfromtheonedescribed intheBellLabsmanualpages:

TheTenthEditionrcdoesnothavetheelsekeyword.Instead,ifisoptionallyfollowedby anifnotclausewhichisexecutediftheprecedingiftestdoesnotsucceed.

BackquotesareslightlydifferentinTenthEdition rc: a backquote must always be followed by aleft-brace.Thisrestrictionisnotpresentforsingle-wordcommandsin thisrc.

For.0file,theTenthEditionrcsearches$path0forfile.Thisrcdoesnot,sinceitisnot considereduseful.

Thelistflatteningoperator,$ˆfoo,0isspelt$"foo0inthoseversionsoftheBell Labs rcwhichhaveit.

The following are all new with this versionofrc:The-n0flag,herestrings(they facilitateexportingoffunctionswithhere documents into the environment), the return andbreakkeywords,theechobuiltin,thebqstatus0andversion0variables,the prompt0function,supportforGNUreadlineandotherlineediting libraries. This rc alsosets$00tothenameofafunctionbeingexecuted/filebeingsourced.

SEEALSO

“rc —AShellforPlan9andUNIXSystems”,UnixResearchSystem,TenthEdition,Volume2. (SaundersCollegePublishing)

http://static.tobold.org/rc/rc-duff.html,0anupdatedversionoftheabovepaper.

history(1)