Get return value of `\write18`

A very elementary approach using shell facilities:

Write the script execution state (either of the script itself or of the last command to an external file using > redirection and then read this generated file to a \def\foomacro.

\documentclass{book}

\newread\myscriptresult

\begin{document}
\immediate\write18{./myscript.sh; echo $? > scriptresult.txt}
\immediate\openin\myscriptresult=scriptresult.txt
\read\myscriptresult to \ScriptResult
\immediate\closein\myscriptresult

The result was \ScriptResult

\end{document}

myscript.sh:

#!/bin/bash

ls -la

The following MWE show how you can directly \input from, say, the date command. It also shows how to \read the output of date in a control sequence, by means of \openin.

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}

\newread\teststream
\newcommand*\testline{}
\openin\teststream=|date
\ifeof\teststream
    \typeout{Unable to open test stream.}
\else
    \typeout{Test stream opened.}
    \read\teststream to \testline
    \typeout{\testline}
\fi

\begin{document}
\input{|date}
\end{document}

However, to avoid problems with special characters, it is probably better to use \readline innstead of \read, if you are running with e-TeX extensions enabled (as you ordinarily do, nowadays).

Of course, the above code requires that you enable the shell-escape feature.

Addition

I think it may be useful to add references to a couple of related (questions and) answers: first of all (and above all) there is Write18: capturing shell (script) output as command/variable?; however, none of the answers to this question (or to this other, related one) mention the fact that the “piped input” feature also works with \openin. For this reason, I take the liberty to cite also Include/input every subfile from a subfolder, even if it includes an answer by myself (and this surely qualifies as self-promotion, which isn’t very nice -- please be forgiving).

Tags:

Shell Escape