Let's say I compile the following file with pdflatex -shell-escape test.tex
:
\documentclass{minimal}
\begin{document}
File listing is:
\immediate\write18{ls /usr}
\end{document}
This will send the output of the command ls /usr
to report/log of pdflatex
(primarily to stdout
).
There are then two cases I'd like to utilize:
- The output of
ls /usr
being included directly in the document (LaTeX stream). - The output of
ls /usr
becoming the contents of a\newcommand
(by this I mean, that I'd like the script to be executed when the\newcommand
is executed first - and upon subsequent calls to the new command, the shell code should not be executed anew).
I have read through How to execute shell script from LaTeX?, but I'm not sure if this "pipe input" can be applied to \newcommand
.
I have also read through tex - How can I save shell output to a variable in LaTeX? - and it seems that Tex' file I/O should be used; but I'm quite disliking the fact that I'd still have to redirect the script output (actually, in this case, the ls /usr
output) to a file, and then read it in, to have it as contents of a command.
So, is there an easier way to achieve what I'd want (hopefully, illustrated through an example based on the above code)?
EDIT: Ehm, I should have asked one more question earlier :) I'll try with an edit here, although it will probably get missed .. :)
I originally asked for a \newcommand
that will execute shell code only upon its definition (i.e., in a sense it is "cached"); and the answer from @egreg does exactly that. But then - would it be possible to have a different \newcommand
definition, such that each time this newcommand is called, the shell command is executed anew? I.e. executing something like \@@input|"cat tempfile"
(which cannot be executed as such), where tempfile
changes between calls?
\newcommand{\foo}{\@@input|"cat tempfile"}
(protect it with\makeatletter
and\makeatother
; each call of\foo
will run the shell command.