/
4OtherCommands95Customization105.1PackageOptions.........105.2CommandO 4OtherCommands95Customization105.1PackageOptions.........105.2CommandO

4OtherCommands95Customization105.1PackageOptions.........105.2CommandO - PDF document

phoebe-click
phoebe-click . @phoebe-click
Follow
369 views
Uploaded On 2016-10-13

4OtherCommands95Customization105.1PackageOptions.........105.2CommandO - PPT Presentation

documentclassarticle usepackagea6papergeometry usepackagebashful pagestyleempty begindocument Thedirectoriesinmytextttusrdirectoryare bashstdout lsFusr END Thatsit endd ID: 475329

\documentclass{article} \usepackage[a6paper]{geometry} \usepackage{bashful} \pagestyle{empty} \begin{document} Thedirectoriesinmy\texttt{/usr}directoryare: \bash[stdout] ls-F/usr \END That'sit! \end{d

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "4OtherCommands95Customization105.1Packag..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

4OtherCommands95Customization105.1PackageOptions.........105.2CommandOptions........105.2.1Filenames........115.2.2ListingStructure.....115.2.3TolerancetoErrors....115.2.4Appearance........115.2.5Miscellaneous.......125.3ListingsStyles...........125.3.1ListingsStyleforScriptFile............125.3.2ListingsStyleforStan-dardOutput.......126InteractionwithOtherPackages137History138Future139Acknowledgments13ASourceofbashful.sty14BSourceofbashful.tex221IntroductionAtthetimeIrunthisdocumentthroughLATEX,thetemperatureinJerusalem,Israel,was17‰,whiletheweatherconditionwasclear.Youmaynotcaresomuchaboutthesebitsoftrulyephemeralinformation,butyoumaybesurprisedthattheywereproducedbytheveryprocessofLATEXingtheinput.BeforeItellyouhowIgeneratedthisinformation,letmedemonstratetheuseofthebashfulpackageforthepurposeofincorporatingthelistof lesinafolderintoyouroutput.ThissimpleLATEX legeneratesalistingofall lesinthe/usrdirectory,usingtheUNIXlscommand: \documentclass{article} \usepackage[a6paper]{geometry} \usepackage{bashful} \pagestyle{empty} \begin{document} Thedirectoriesinmy\texttt{/usr}directoryare: \bash[stdout] ls-F/usr \END That'sit! \end{document}  Theprintedoutputofthis leisthen2 Togeneratetheweatherinformation,Iwroteaseriesofshellcommandsthatretrievethecurrenttemperature,andanothersuchseriestoobtainthecurrentweatherconditions.ThistaskrequiredconnectiontoGoogle'sweatherserviceandminimaldexteritywithUnixpipesand lterstoprocesstheoutput.Mycommandseriestoobtainthecurrenttemperaturewas:%location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\greptemp_c|\sed's/[^0-9]//g'whiletheweatherconditionwasobtainedby%location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\grep"conditiondata"|\head-n1|\sed-e's/^.*="//'-e's/"\/*//'|\tr'A-Z''a-z'ThesecondstepwascoercingLATEXtorunthesecommandswhileprocessingmydocument.Todothat,Iusedpackagebashful,\usepackage{bashful}And,then,Iwrappedeachofthesetwoserieswithina\bash...\ENDpair.The\bashcommand,o eredbythispackage,takesallsubsequentlines,stoppingattheclosing\END,placestheseina le,andthenletsthebashshellinterpreterexecutethis le.AllowingLATEXtorunarbitraryshellcommandscanbedangerous|youneverknowwhetherthatnicelooking.tex leyoureceivedbyemailwaspreparedbyafriendorafoe.ThisisthereasonthatyouhavetotellLATEXexplicitlythatshell3 escapesareallowed.The-shell-esc agdoesthat.Toprocessmydocument,Ityped,atthecommandline,%latex-shell-escapebashful.texWhatIactuallywroteintheinputtoproducethetemperatureinJerusalem,Israelwas:\bash[verbose,scriptFile=temperature.sh,stdoutFile=temperature.tex]%location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\greptemp_c|\sed's/[^0-9]//g'\ENDThe agspassedtothebashcontrolsequenceaboveinstructedit:1.tobeverbose,typingoutadetailedlogofeverythingitdid;2.tosavetheshellcommandsinascript lenamedtemperature.sh;and,3.tostorethestandardoutputofthescriptina lenamedtemperature.tex.ToobtainthecurrentweatherconditioninthecapitalIwrote:\bash[verbose,scriptFile=condition.sh,stdoutFile=condition.tex]%location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\grep"conditiondata"|\head-n1|\sed-e's/^.*="//'-e's/"\/*//'|\tr'A-Z''a-z'\ENDIwrotethesetwojustaftermy\begin{document}.WhenLATEXencounteredthese,itexecutedthebashcommandsandcreatedtwo lestemperature.texandcondition.tex.Subsequently,Icouldusethecontentofthese lesbywriting:AtthetimeIrunthisdocumentthrough\LaTeX{},thetemperatureinJerusalem,Israel,was~\emph{\input{temperature}\unskip\celsius},whiletheweatherconditionwas\emph{\input{condition}}\unskip.Youmaynotcaresomuchaboutthesebitsoftruly...4 \bash[script,stdout]./a.out\ENDtoruntheprogramIjustwrote.Thestdoutaddstomylistingtheoutputthatthisexecutionproduces,i.e.,thestringHello,World!thatthisexecutionproducestothestandardoutput.3DealingWithErrorsUsingbashfultodemonstratemyHello,World!program,madesurethatthestoryItoldisaccurate:IreallydideverythingIsaidIdid.Moreaccurately,the\bashcommandactedasmyproxy,anddiditforme.Luckily,myhello.cprogramwascorrect.But,ifitwasnot,the\bashcom-mandwouldhavedetectedtheerror,andwouldhavestoppedtheLATEXprocess,indicatingthatthecompilationdidnotsucceed.Morespeci cally,the\bashcommand1.collectsallcommandsupto\END;2.placesthesecommandsinascript le;3.changedirectorytoadesignateddirectoryifthehideoptionisset(thediroptionsetsthedirectoryname);4.executesthisscript le,redirectingitsstandardoutputanditsstandarderrorstreamstodistinct les;5.checkswhethertheexitcodeoftheexecutionindicatesanerror(i.e.,exitcodewhichisdi erentfrom0),andifso,placethisexitcodeinadistinct le;6.checkswhetherthe lecontainingthestandarderrorisempty,andifnot,pausesexecutionafterdisplayinganerrormessage;7.checkswhetherthe lecontainingtheexitcodeisempty,andifnot,pausesexecutionafterdisplayinganerrormessage;8.lists,ifrequestedto,thescript le;9.lists,ifrequestedto,the lecontainingthestandardoutput;and,10.lists,ifrequestedto,the lecontainingthestandarderror;Letmedemonstrateasituationinwhichtheexecutionofthescriptgeneratesanerror.Todothat,IwillwriteashortLATEX le,namedminimal.texwhichtriestouse\bashtocompileanincorrectCprogram.Sinceminimal.texcontains\END,Iwillhavetoauthorthis leinthreesteps:7 fileminimal.stderrbegins:����error.c:Infunctionmain:����but,youreallyoughttoexaminethisfileyourself!!Yourshellscriptfailed....\checkScriptErrors@BL...rshellscriptfailed...}\BL@verbosetrue\logBL{Sw...l.11\END?OK,entering\batchmodeYoucanseethatwhenLATEXtriedtoprocessminimal.tex,itstoppedexecutionwhileindicatingthat leminimal.stderrwasnotemptyafterthecompilation.The rstlineofminimal.stderrwasdisplayed,andIwasadvisedtoexaminethis lemyself.Inspectingminimal.stderr,weseetheCcompilererrormessages:%catminimal.stderrerror.c:Infunctionmain:error.c:1:15:error:expectedexpressionbeforeintNotethatthefailuretocompilehello.c,didnotstop\bashfromincludingthis leinthesource.Hereiswhatminimal.pdflookslike: 4OtherCommandsnbashStdoutAftereachexecutionof\bash,themacro\bashStdoutisde nedtoentirecontentsofthestandardoutputoftheexecutedscript.Forexample,IcanwriteToobtainthefollowingsentence:\bashuname-o\END\begin{quote}``Thisdocumentwaspreparedon\emph{\bashStdout}''\end{quote}Toobtainthefollowingsentence:\ThisdocumentwaspreparedonGNU/Linux"nbashStderrSimilarto\bashStderr,exceptthatitisde nedisde nedtothestandarderroroftheexecutedscript.(Bewarethatyoumustapplyerror9 the\bashcommandwasinvoked,andEXTENSIONisoneof\sh",\stdout",\stderr"and\exitCode.Iffalse,thenthese lesfollowthepatternJOB.EXTENSION.Youshouldusethisoptionyourinputinvokes\bashmorethanonce.dir=hdirectoryNameiIfhideoptionistrue,thenscriptsareexecutedinthisdirectory.Initialvalueofthisoptionsis_00.NotethatifyouuseTEXlive,youhavetocon gurecertainsecurity agstomakeitpossibletowritetodirectorieswhosenamestartwithadot,ortodirectorieswhicharenotbelowthecurrentworkingdirectory.5.2CommandOptionsOptionsto\bashcommandarepassedusingthexkeyvalsyntax:5.2.1FilenamesscriptFile=h leNameinjobname.shNameof leintowhichthescriptinstructionsarespilledpriortoexecution.Thedefaultis\jobname.sh;this lewillbereusedbyall\bashcommandsinyourdocuments.Thisisrarelyaproblem,sincethesescriptsexecutesequentially.stdoutFile=h leNameinjobname.stdoutNameof leintowhichtheshellstandardoutputstreamisredirected.stderrFile=h leNameinjobname.stderrNameof leintowhichtheshellstandarderrorstreamisredirected.exitCodeFile=h leNameinjobname.stderrNameof leintowhichtheshellstandarderrorstreamisredirected.5.2.2ListingStructurescript=htrue/falseifalseIftrue,thecontentofscriptFileislistedinthemaindocument.stdout=htrue/falseifalseIftrue,thecontentofstdoutFileislistedinthemaindocument.Ifbothscriptandstdoutaretrue,thenscriptFileislisted rst,andleavingnoverticalspace,stdoutFileislistednext.stderr=htrue/falseifalseIftrue,thecontentofstderrFileislistedinthemaindocument,followingscriptFile(ifscriptistrue)andstdoutFile(ifstdoutistrue).11 5.3.2ListingsStyleforStandardOutputStylebashfulStdoutisusedfordisplayingtheoutputoftheexecutedshellcom-mands(whenoptionstdoutisused).Thecurrentde nitionis:%listingsstyleforthestdoutFile,canberedefinedbyclient\lstdefinestyle{bashfulStdout}{basicstyle=\sl\ttfamily,keywords={},showstringspaces=false}%Rede nethisstyletomatchyourneeds.StylebashfulStderrisusedfordisplayingtheoutputoftheexecutedshellcommands(whenoptionstderrisused).\lstdefinestyle{bashfulStderr}{basicstyle=\sl\ttfamily\color{red},keywords={},showstringspaces=false}Rede nethisstyletomatchyourneeds.6InteractionwithOtherPackagesThispackagestriestoworkaroundabuginpolyglossiabywhich\textttisgarbleduponswitchingtolanguageswhichdonotusetheLatinalphabet.Also,incasebidirectionalTEXingisine ect,bashfulforcesthelistingtobeleft-to-right.7HistoryVersion0.91Initialrelease.Version0.92ˆAddedignoreExitCode,ignoreStderr,stderr,exitCodeFilecommandoptions.ˆRenamedlisttoscript.ˆAddedhideanddirpackageoptions.Version0.93ˆAddedtheuniquepackage ag.ˆAddedthe\splice,\bashStdoutand\bashStderrcommands.ˆEnclosedinthepackagingthePracTEXarticlesourceand.pdf le.13 \RequirePackage{catchfile}\RequirePackage{xkeyval}%Usexkeyvalforretrievingparameters\RequirePackage{textcomp}%Forupquote40%Iftrue,allactivitiestakeplaceinadesignateddirectory.\newif\if@hide@BL@\@hide@BL@false%\if@unique@BL@isaBooleanflag,tellinguswhetheruniquenamesshouldbe%generatedfortheauxiliaryfiles(XX.sh,XX.stdout,XX.stderrand%XX.exitCode)ineachinvocationofthe\bashcommand.\newif\if@unique@BL@\@unique@BL@false\def\unique@BL{\if@unique@BL@@\the\inputlineno\fi}%Thisisthedefaultnameforadirectoryinwhichprocessingshould50%takeplaceif\@hide@BL@true.\def\directory@BL{_00}%Uselistingtodisplaybashscripts.\RequirePackage{listings}%%listingsstyleforthescript,canberedefinedbyclient\lstdefinestyle{bashfulScript}{basicstyle=\ttfamily,keywords={},60upquote=true,showstringspaces=false}%%listingsstyleforthestandardoutputfile,canberedefinedbyclient\lstdefinestyle{bashfulStdout}{basicstyle=\sl\ttfamily,keywords={},upquote=true,showstringspaces=false}%%listingsstyleforthestandarderrorfile,canberedefinedbyclient70\lstdefinestyle{bashfulStderr}{basicstyle=\sl\ttfamily\color{red},keywords={},upquote=true,showstringspaces=false}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Keysgeneratingfilenamesinalphabeticalorder:80%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%dir:String=\directory@BL:Nameofdirectoryinwhichexecutionisgoing%totakeplace\define@cmdkey{bashful}[BL@]{dir}{\def\directory@BL{#1}}%%exitCodeFile:String=\BL@exitCodeFile:Inwhichfileshouldtheexitcode%bestoredifitisnotzero.\def\BL@exitCodeFile{\jobname\unique@BL.exitCode}%\define@cmdkey{bashful}[BL@]{exitCodeFile}{}%90%scriptFile:String=\BL@scriptFile:Inwhichfileshouldthescriptbe%saved?\def\BL@scriptFile{\jobname\unique@BL.sh}%\define@cmdkey{bashful}[BL@]{scriptFile}{}%%stderrFile:String=\BL@stderrFile:Inwhichfileshouldthestandard%errorstreambesaved?\def\BL@stderrFile{\jobname\unique@BL.stderr}%\define@cmdkey{bashful}[BL@]{stderrFile}{}%100%stdoutFile:String=\BL@stdoutFile:Inwhichfileshouldthestandard%outputstreambesaved?\def\BL@stdoutFile{\jobname\unique@BL.stdout}%15 \define@cmdkey{bashful}[BL@]{stdoutFile}{}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Listconfigurationbooleankeys%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%110%list:Boolean=\ifBL@script:Shouldwelistthescriptwegenerate?\define@boolkey{bashful}[BL@]{script}[true]{}%%stdout:Boolean=\ifBL@stderr:Shouldwelistthestandarderror?\define@boolkey{bashful}[BL@]{stderr}[true]{}%%stdout:Boolean=\ifBL@stdout:Shouldwelistthestandardoutput?\define@boolkey{bashful}[BL@]{stdout}[true]{}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%120%ErrorcheckingBooleankeys.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%stdout:Boolean=\ifBL@ignoreExitCode:Shouldweignoretheexit%code?\define@boolkey{bashful}[BL@]{ignoreExitCode}[true]{}%stdout:Boolean=\ifBL@ignoreStderr:Shouldweignoretheexit%code?\define@boolkey{bashful}[BL@]{ignoreStderr}[true]{}130%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Miscelaneouskeys%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%environment:String=\BL@environment:Whichenvironmentshouldwewrap%thelistings\def\BL@environment{none@BL}%\define@cmdkey{bashful}[BL@]{environment}{}%\newenvironment{none@BL}{}{}%Default,emptyenvironmentforwrapping140%thelistings%prefix:String=\BL@prefix:Whatprefixshouldbeprintedbeforealisting.\def\BL@prefix{\@percentchar\space}%\define@cmdkey{bashful}[BL@]{prefix}{}%%shell:String=\BL@shell:Whichshellshouldbeusedforexecution?\def\BL@shell{bash}%\define@cmdkey{bashful}[BL@]{shell}{}%150%verbose:Boolean=\ifBL@verbose:Logeverystepwedo\define@boolkey{bashful}[BL@]{verbose}[true]{}%%The"unique"packageflagthattellsthepackagetogenerateduniquenames%fortheauxiliaryfiles.Iftruethegeneratedfiles(XX.sh,XX.stdout,%XX.stderrandXX.exitCode)aregivenuniquenamesineachinvocationofthe%\bashcommand.UniquenamesaregeneratedbythepatternJOB@LINE.EXTENSION,%whereJOBisthejob'sname,LINEisthenumberofthelineintheinputin%whichthe\bashcommandwasinvoked,andEXTENSIONisoneof"sh","stdout",%"stderr"and"exitCode".160\DeclareOptionX{unique}{\@unique@BL@true}\DeclareOptionX{hide}{\@hide@BL@true}\DeclareOptionX{dir}{\@hide@BL@true\def\directory@BL{#1}}\DeclareOptionX{verbose}{\BL@verbosetrue}\ExecuteOptionsX{}\ProcessOptionsX\relax%\bash:themaincommandwedefine.Itchainsto\bashIwhichchainsto%\bashII,etc.170\begingroup%\where@BL16 \catcode`\^^M\active%\gdef\bash{%\logBL{Beginningagroupsothatallcatcodechangesarelocal}%\begingroup%\logBL{Making\^\^Matruenewline}%\catcode`\^^M\active%\def^^M{^^J}%\logBL{Checkingforoptionalarguments}%180\@ifnextchar[{\bashI}{\bashI[]}%}%\endgroup%\bashI:Processtheoptionalargumentsandcontinue\def\bashI[#1]{\setKeys@BL{#1}\bashII}%\bashII:Setcategorycodesofallcharacterstospecial,andproceed.\begingroup\catcode`\^^M\active%190\gdef\bashII{%\logBL{bashII:Making\^\^Matruenewline}%\catcode`\^^M\active%\def^^M{^^J}%\logBL{bashII:Makingallcharactersother}%\let\do\@makeother%\dospecials%\bashIII}%\endgroup200%\bashIII:Consumealltokensuntil\END(butignoringtheprecedingand%terminatingnewline),andproceed.\begingroup\catcode`\@=0\relax\catcode`\^^M\active@catcode`@\=12@relax%@gdef@bashIII^^M#1^^M%\END{@bashIV{#1}@bashV{#1}@logBL{bashV:Done!}@endgroup}@endgroup%\bashIV:Processthetokensbystoringtheminascriptfile,andexecuting210%thisfile,\newcommand\bashIV[1]{%\logBL{BashIV:begin}%\makeDirectory@BL\generateScriptFile@BL{#1}\relax\executeScriptFile@BL\logBL{BashIV:done}%}%%\logBL:recordalogmessageinverbosemode220\newcommand\logBL[1]{\ifBL@verbose\typeout{L\the\inputlineno:#1}\fi}%Amacrotocreateanewdirectory\def\makeDirectory@BL{%\if@hide@BL@\logBL{Makingdirectory\directory@BL}%\immediate\write18{mkdir-p\directory@BL}%\else\logBL{Usingcurrentdirectory}%\fi230}\newcommand\splice[1]{%\bashIV{#1}%\expandFileName@BL{\BL@stdoutFile}%\CatchFileDef{\BL@file@contents}{\BL@stdoutFile}{\relax}%\ignorespaces\BL@file@contents\unskip}%listingthescriptfileifrequired,andpresentingthestandardoutputand17 240%standarderrorfilesifrequired.\newcommand\bashV[1]{%\logBL{Wrappingupafterexecution}%\storeToFile@BL{\BL@prefix#1}{\BL@scriptFile}%\expandFileName@BL\BL@scriptFile\expandFileName@BL\BL@stdoutFile\expandFileName@BL\BL@stderrFile\logBL{Filesare:\BL@scriptFile,\BL@stdoutFile,and\BL@stderrFile}%\checkScriptErrors@BL\listEverything@BL250\defineMacros@BL\logBL{Wrapupdone}}\def\expandFileName@BL#1{%\logBL{Setting,ifnecessary,correctpathof\noexpand#1}%\if@hide@BL@\logBL{Prependingpath(\directory@BL)to#1}%\edef#1{\directory@BL/#1}%\logBL{Obtained#1}%\fi260}\def\setKeys@BL#1{%\logBL{Processingkey=valpairsinoptionsstring[#1]}\relax\setkeys{bashful}{#1}%}%%Storethelistoftokensinthefirstargumentintoourscriptfile\newcommand\generateScriptFile@BL[1]{%\logBL{Generatingscriptfile\BL@scriptFile}270\storeToFile@BL{#1}{\BL@scriptFile}%}%\newwrite\writer@BL%Storethelistoftokensinthefirstargumentintothefilegiven%inthesecondargument;prependdirectoryifnecessary\newcommand\storeToFile@BL[2]{%\logBL{#2:=^^J#1^^J}%\if@hide@BL@\logBL{File#2willbecreatedin\directory@BL}%280\storeToFileI@BL{#1}{\directory@BL/#2}\else\logBL{File#2willbecreatedincurrentdirectory}%\storeToFileI@BL{#1}{#2}%\fi\logBL{Writingdone!}%}%%Storethelistoftokensinthefirstargumentintothefilegiven%inthesecondargument;thesecondargumentcouldbequalifiedwith290%adirectoryname.\newcommand\storeToFileI@BL[2]{%\logBL{Writingtofile#2...}%\immediate\openout\writer@BL#2%\immediate\write\writer@BL{#1}%\immediate\closeout\writer@BL}%%Executethecontentofourscriptfile.\newcommand\executeScriptFile@BL{%300\edef\command@BL{\BL@shell\space\BL@scriptFile}%\if@hide@BL@\logBL{Addinga"cdcommand"}%\edef\command@BL{cd\directory@BL;\command@BL}\fi%\edef\command@BL{\command@BL\space�\BL@stdoutFile\space2�\BL@stderrFile}%\edef\command@BL{\command@BL\space||echo$?�\BL@exitCodeFile}%\edef\command@BL{\BL@shell\space-c"\command@BL"}%18 \logBL{bashStderr:=^^J\bashStderr^^J}%\endgroup\logBL{Closingfile\BL@stderrFile}%\immediate\closein\reader@BL}\newcommand\fixPolyglossiaBug@BL{%\logBL{TryingtofixaPolyglossiapackagebug}%520\ifdefined\ttfamilylatin\logBL{Replacing\noexpand\ttfamilywith\noexpand\ttfamilylatin}%\let\ttfamily=\ttfamilylatin\logBL{Replacing\noexpand\rmfamilywith\noexpand\rmfamilylatin}%\let\rmfamily=\rmfamilylatin\logBL{Replacing\noexpand\sffamilywith\noexpand\sffamilylatin}%\let\sffamily=\sffamilylatin\logBL{Replacing\noexpand\normalfontwith\noexpand\normalfontlatin}%\let\normalfont=\normalfontlatin\else530\logBL{Polyglossiapackageprobablynotloaded}%\relax\fi}%\newcommand\forceLTR@BL{%\logBL{Makingsurewearenotinright-to-leftmode}%\ifdefined\setLTR\logBL{Command\noexpand\setLTRisdefined,invokingit}%\setLTR540\else\logBL{Command\noexpand\setLTRisnotdefined,weareprobablyLTR}%\relax\fi}%BSourceofbashful.tex1\documentclass{ltxdoc}%Processwithxelatex-shell-escape\usepackage[verbose,unique]{bashful}\usepackage[colorlinks=true]{hyperref}\usepackage{gensymb}\usepackage{graphicx}\usepackage{metalogo}\usepackage{xkvview}\usepackage{xspace}10\usepackage{amsmath}\usepackage{multicol}\newcommand\me{bashful}\newcommand\bashful{\textsf{\me}\xspace}\lstdefinestyle{input}{basicstyle=\ttfamily\footnotesize,keywords={},upquote=true,extendedchars=false,showstringspaces=false,aboveskip=0pt,belowskip=0pt}\lstdefinestyle{scriptsize}{style=input,basicstyle=\ttfamily\scriptsize}20%listingsstyleforthescript,standardoutputfile,andstandarderrorfile.\lstdefinestyle{bashfulScript}{style=input}\lstdefinestyle{bashfulStdout}{style=input}\lstdefinestyle{bashfulStderr}{style=input,basicstyle=\ttfamily\footnotesize\color{red}}\newcommand\listFile[1]{%\vspace{0.8emplus0.3emminus0.3em}%\lstinputlisting[style=input,frameround=ftttt,frame=trBL]{#1}%\vspace{0.8emplus0.3emminus0.3em}}30\title{The\bashfulPackage\thanks{Copyright\copyright{}2011,2012byYossiGil22 \url{mailto:yogi@cs.technion.ac.il}.Thisworkmaybedistributedand/ormodifiedundertheconditionsofthe\emph{\LaTeX{}ProjectPublicLicense}(LPPL),eitherversion1.3ofthislicenseor(atyouroption)anylaterversion.Thelatestversionofthislicenseisin\url{http://www.latex-project.org/lppl.txt}andversion1.3orlaterispartofalldistributionsof\LaTeX{}version2005/12/01orlater.ThisworkhastheLPPLmaintenancestatus`maintained'.40TheCurrentMaintainerofthisworkisYossiGil.Thisworkconsistsofthefiles\texttt{\me.tex}and\texttt{\me.sty}andthederivedfile\texttt{\me.pdf}}}\author{YossiGil\thanks{\url{mailto:yogi@cs.Technion.ac.IL}}\\\normalsizeDepartmentofComputerScience\\\normalsizeTheTechnion---IsraelInstituteofTechnology\\\normalsizeTechnionCity,Haifa32000,Israel50}\makeatletter\date{\date@bashful\thanks{Thisdocumentdescribes\bashful\version@bashful.}}\makeatother\begin{document}\bashcatEOF&#x-759;README60Thebashfulpackage,v0.93ThispackagemakesitpossibletoexecutebashscriptsfromwithinLaTeX.Themainapplicationisinwritingcomputer-sciencetexts,inwhichyouwanttomakesuretheprogramslistedinthedocumentareexecuteddirectlyfromtheinput.Thispackagemaybedistributedand/ormodifiedundertheLaTeXProjectPublicLicense,version1.3orhigher(yourchoice).Thelatestversionofthislicenseisat:http://www.latex-project.org/lppl.txt70Thisworkisauthor-maintained(asperLPPLmaintenancestatus)byYossiGil,yogi@cs.Technion.ac.i&#x-128;EOF\END\bash[verbose,stdoutFile=bashful.date]stat-c%ybashful.sty|sed-es+-+/+g-e's/.*//g'&#x-128;date\END80\maketitle\begin{abstract}\parindent1.5ex\parskip0.5em\slItissometimesusefulto``\emph{escape-to-shell}''fromwithin\LaTeX{}.Themostobviousapplicationiswhenthedocument90explainssomethingabouttheworkingofacomputerprogram.Yourtextwouldbemorerobusttochanges,andeasiertowrite,ifalltheexamplesitgives,arerundirectlyfromwithin\LaTeX{}.Tofacilitatethisandotherapplications,package\bashful{}providesaconvenientinterfaceto\TeX'sprimitive\verb+\write18+---theexecutionofshellcommandsfromwithinyourinputfiles,alsoknownas\emph{shellescape}.Textbetween\verb+\bash+and\verb+\END+isexecutedby23 100\href{http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29}{\texttt{bash}},apopularUnixcommandlineinterpreter.Variousflagscontrolwhethertheexecutedcommandsandtheiroutputshowupintheprinteddocument,andwhethertheyaresavedtofiles.Althoughprovisionsaremadeforusingshellsotherthan\texttt{bash},thispackagemay\emph{not}operatewithout110modificationsonMicrosoft'soperatingsystems.\end{abstract}\begin{multicols}{2}\footnotesize\tableofcontents\end{multicols}\parindent1.5ex\parskip0.5em120\section{Introduction}\bash[verbose,scriptFile=temperature.sh,stdoutFile=temperature.tex]location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\greptemp_c|\130sed's/[^0-9]//g'\END\bash[verbose,scriptFile=condition.sh,stdoutFile=condition.tex]location=Jerusalem,Israelserver="http://www.Google.com/ig/api"request="$server?weather=$location"wget-q-O-$request|\tr"&#x-122;""\012\012"|\grep"conditiondata"|\140head-n1|\sed-e's/^.*="//'-e's/"\/*//'|\tr'A-Z''a-z'\ENDAtthetimeIrunthisdocumentthrough\LaTeX{},thetemperatureinJerusalem,Israel,was~\emph{\input{temperature}\unskip\celsius},whiletheweatherconditionwas\emph{\input{condition}}\unskip.150Youmaynotcaresomuchaboutthesebitsoftrulyephemeralinformation,butyoumaybesurprisedthattheywereproducedbytheveryprocessof\LaTeX{}ingtheinput.\bashcatEOF&#x-760;ls.tex\documentclass{article}\usepackage[a6paper]{geometry}160\usepackage{bashful}\pagestyle{empty}\begin{document}Thedirectoriesinmy\texttt{/usr}directoryare:\bash[stdout]ls-F/usrEOFecho"\\END"&#x-760;&#x-760;ls.tex24 catEOF&#x-759;&#x-759;ls.texThat'sit!170\end{document}EOFxelatex-shell-escapels.tex\ENDBeforeItellyouhowIgeneratedthisinformation,letmedemonstratetheuseofthe\bashfulpackageforthepurposeofincorporatingthelistoffilesinafolderintoyouroutput.Thissimple\LaTeX{}filegeneratesalistingofallfiles180inthe\texttt{/usr}directory,usingtheUNIX\texttt{ls}command:\begin{minipage}{\textwidth}\listFile{ls.tex}\end{minipage}Theprintedoutputofthisfileisthen\begin{center}190\fbox{\includegraphics[scale=0.8,trim=202004050]{ls.pdf}}\end{center}Togeneratetheweatherinformation,Iwroteaseriesofshellcommandsthatretrievethecurrenttemperature,andanothersuchseriestoobtainthecurrentweatherconditions.Thistaskrequiredconnectionto\href{http://www.Google.com/support/forum/p/%apps-apis/thread?tid=0c95e45bd80def1a&hl=en}%200{Google'sweatherservice}andminimaldexteritywithUnixpipesandfilterstoprocesstheoutput.Mycommandseriestoobtainthecurrenttemperaturewas:\begin{minipage}{\textwidth}\begin{quote}\lstinputlisting[style=input]{temperature.sh}\end{quote}\end{minipage}210whiletheweatherconditionwasobtainedby\begin{minipage}{\textwidth}\begin{quote}\lstinputlisting[style=input]{condition.sh}\end{quote}\end{minipage}Thesecondstepwascoercing\LaTeX{}torunthesecommands220whileprocessingmydocument.Todothat,Iusedpackage\bashful,\begin{verbatim}\usepackage{bashful}\end{verbatim}And,then,Iwrappedeachofthesetwoserieswithina\verb+\bash+\ldots\verb+\END+pair.The\verb+\bash+command,offeredbythispackage,takesallsubsequentlines,stoppingattheclosing\verb+\END+,230placestheseinafile,andthenletsthe\texttt{bash}shellinterpreterexecutethisfile.Allowing\LaTeX{}torunarbitraryshellcommandscanbedangerous---youneverknowwhetherthatnicelooking\texttt{.tex}fileyoureceivedbyemailwaspreparedbyafriendor25 440\begin{enumerate}\itemcollectsallcommandsupto\verb+\END+;\itemplacesthesecommandsinascriptfile;\itemchangedirectorytoadesignateddirectoryifthe\texttt{hide}optionisset(the\texttt{dir}optionsetsthedirectoryname);\itemexecutesthisscriptfile,redirectingitsstandardoutputanditsstandarderrorstreamstodistinctfiles;\itemcheckswhethertheexitcodeoftheexecutionindicatesanerror(i.e.,exitcodewhichisdifferentfrom~$0$),andifso,placethisexitcodeinadistinctfile;450\itemcheckswhetherthefilecontainingthestandarderrorisempty,andifnot,pausesexecutionafterdisplayinganerrormessage;\itemcheckswhetherthefilecontainingtheexitcodeisempty,andifnot,pausesexecutionafterdisplayinganerrormessage;\itemlists,ifrequestedto,thescriptfile;\itemlists,ifrequestedto,thefilecontainingthestandardoutput;and,\itemlists,ifrequestedto,thefilecontainingthestandarderror;\end{enumerate}Letmedemonstrateasituationinwhichtheexecutionof460thescriptgeneratesanerror.Todothat,Iwillwriteashort\LaTeX{}file,named\texttt{minimal.tex}whichtriestouse\verb+\bash+tocompileanincorrect~Cprogram.Since\texttt{minimal.tex}contains\verb+\END+,Iwillhavetoauthorthisfileinthreesteps:\begin{enumerate}\itemCreatingtheheaderof\texttt{minimal.tex}:\bash[script]catEOF&#x-759;minimal.tex\documentclass{article}470\usepackage[a6paper]{geometry}\usepackage{bashful}\pagestyle{empty}\begin{document}ThisdocumentcreatesasimpleerroneousCprogramandthencompilesit:\bash[script,stdout]echo"main(){returnint;}"&#x-759;error.cccerror.cEOF480\END\itemAdding\verb+\END+to\texttt{minimal.tex}\bash[script]echo"\\END"&#x-759;&#x-759;minimal.tex\END\itemFinalizing\texttt{minimal.tex}\bash[script]echo"\\end{document}"&#x-759;&#x-759;minimal.tex\END\end{enumerate}490Letmenowmakesure\texttt{minimal.tex}waswhatIexpectittobe:\begin{minipage}{\textwidth}\bash[script,stdout]catminimal.tex\END\end{minipage}Iamnowreadytorun\texttt{minimal.tex}through\LaTeX{},500butsinceIwillnotrunthe\texttt{latex}commandmyself,Iwillsenda``\texttt{q}''charactertoittoabortexecutionwhentheanticipatederroroccurs.\lstdefinestyle{bashfulScript}{style=scriptsize}\lstdefinestyle{bashfulStdout}{style=scriptsize}\bash[script,stdout]yesq|xelatex-shell-escminimal.tex|sed/texmf-dist/d29 \END\lstdefinestyle{bashfulScript}{style=input}510\lstdefinestyle{bashfulStdout}{style=input}Youcanseethatwhen\LaTeX{}triedtoprocess\texttt{minimal.tex},itstoppedexecutionwhileindicatingthatfile\texttt{minimal.stderr}wasnotemptyafterthecompilation.Thefirstlineof\texttt{minimal.stderr}wasdisplayed,andIwasadvisedtoexaminethisfilemyself.Inspecting\texttt{minimal.stderr},weseetheCcompilererrormessages:\begin{minipage}{\textwidth}520\bash[script,stdout]catminimal.stderr\END\end{minipage}Notethatthefailuretocompile\texttt{hello.c},didnotstop\verb+\bash+fromincludingthisfileinthesource.Hereiswhat\texttt{minimal.pdf}lookslike:530\begin{center}\fbox{\includegraphics[scale=0.8,trim=303001040]{minimal.pdf}}\end{center}\section{OtherCommands}\begin{description}\item[\texttt{\textbackslash{}bashStdout}]Aftereachexecutionof\verb+\bash+,themacro\verb+\bashStdout+isdefinedtoentirecontentsof540thestandardoutputoftheexecutedscript.Forexample,Icanwrite\begin{quote}\begin{verbatim}Toobtainthefollowingsentence:\bashuname-o\END\begin{quote}550``Thisdocumentwaspreparedon\emph{\bashStdout}''\end{quote}\end{verbatim}\end{quote}Toobtainthefollowingsentence:\bashuname-o\END\begin{quote}``Thisdocumentwaspreparedon\emph{\bashStdout}''560\end{quote}\item[\texttt{\textbackslash{}bashStderr}]Similarto\verb+\bashStderr+,exceptthatitisdefinedisdefinedtothestandarderroroftheexecutedscript.(Bewarethatyoumustapplyerrortoleranceflagstousethiscommand,sincenormally,ifthescriptgeneratesanythingtothestandarderrorstream,\LaTeX{}processingwillhalt,askingforyourattention.)570\item[\texttt{\textbackslash{}splice}]Shellcommandspassedtothe\verb+\splice+macroareexecutedinasimilarfashiontocommandsenclosedbetween\verb+\bash+and\verb+\END+,but,inadditiontothisexecution,\bashfulincorporatesthestandardoutputintothemainfile.30 Forexample,Icanwrite\begin{quote}\begin{verbatim}Hereisanicequoteforyoutoremember.580\begin{quote}\emph{\splice{fortune}}\end{quote}\end{verbatim}\end{quote}Toobtain\begin{quote}Hereisanicequoteforyoutoremember.\begin{quote}\emph{\splice{fortune}}590\end{quote}\end{quote}Unlikethe\verb+\bash+\ldots\verb+\END+,\verb+\splice+doesnottreatitsargumentasifitwas\texttt{verbatim}.Usingspecialcharacterscanthereforebetrickywith\verb+\splice+.Onthepositiveside,macroexpansionwithinthisargumentcanbehandy.600\end{description}\bashcat00.tex|\tr-c"a-zA-Z\\\\""\012"|\tr"\\\\""@"|sed"s/@/@/g"|\tr"""\012"|\sed"/^@$/d"|\grep@|sort|\610uniq-c|\sort-n|\awk'{print$1}'|uniq-c\END620\section{Customization}\newcommand\option[3]{%\noindent\(\text{\bfseries\texttt{#1}}=\langle\text{{#2}}\rangle\)\hfill\texttt{#3}\\}\subsection{PackageOptions}630Optionstothe\verb+\bashful+packagepassedusingthe\textsf{xkeyval}syntax:\option{hide}{\texttt{true}/\texttt{false}}{\texttt{false}}If\texttt{true},scriptsareexecutedinadesignateddirectory;if\texttt{false},scripsareexecutedinthecurrentworkingdirectory.\option{dir}{\sldirectoryName}{}If\texttt{hide}optionis\texttt{true},then640scriptsareexecutedinthisdirectory.Initialvalueofthisoptionsis\verb+_00+.Notethatifyouuse\TeX{}live2010,youhavetoconfigurecertainsecurityflagstomakeitpossibletowritetodirectories31

Related Contents


Next Show more