Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute shell script from LaTeX?

Tags:

shell

latex

I'm trying to do the following in LaTeX:

\documentclass{article} \begin{document} \execute{/usr/local/bin/my-shell-script.sh} \end{document} 

The idea is to execute /usr/local/bin/my-shell-script.sh at the moment of .tex document processing and inject its output into LaTeX stream. Is it possible at all?

PS. It's possible through the package I've made: iexec

like image 935
yegor256 Avatar asked Jul 15 '10 06:07

yegor256


People also ask

Can we run shell script from Java?

If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).


2 Answers

I would do something like the following (partially motivated by what Roman suggested): make your LaTeX file be

\documentclass{article} \begin{document} \input{scriptoutput.tex} \end{document} 

and generate the file scriptoutput.tex using

/usr/local/bin/my-shell-script.sh > scriptoutput.tex 

You could encode this in a makefile if you want to have it run automatically when necessary. Alternatively, you could use the TeX \write18 command,

\documentclass{article} \immediate\write18{/usr/local/bin/my-shell-script.sh > scriptoutput.tex} \begin{document} \input{scriptoutput.tex} \end{document} 

and I think that would automatically run the shell script each time you compile the document. The \immediate is necessary to ensure that the script is run when LaTeX encounters the command, rather than waiting until a page of output is written. (See this question for more on the shipout routine.)

like image 196
David Z Avatar answered Sep 29 '22 17:09

David Z


As David pointed out, you can use \write18 to call external programs, then \input the resultant output file. However you will probably want to use \immediate\write18 to make sure the script is executed before calling the \input.

Alternatively, if you use newer versions of pdf(la)tex (after 1.40, I think), you can pipe the output directly into the document, by using a piped input command:

\documentclass{article} \begin{document} \input{|"/usr/local/bin/my-shell-script.sh"} \end{document} 

For either method you will need to enable external program calls. For TeXlive distributions, you need to call latex with the -shell-escape option, or for MikTeX, I believe the option is -enable-write18.

like image 23
Simon Byrne Avatar answered Sep 29 '22 16:09

Simon Byrne