# Macro expansion in \write

I want to use a macro in \write18, but this causes the space after it to be ignored. The following example prints foobar to test.txt, whereas I want it to print foo bar:

\documentclass{standalone}
\newcommand*{\foo}{foo}
\begin{document}
\write18{echo \foo bar > test.txt}
\end{document}


I tried {\foo}, \foo{}, and \foo\ instead of just \foo, but these all print the braces and slashes to the file, which is not what I want. How can I expand the macro without introducing extra characters, and without removing the space?

The example above is of course simplified. In my real scenario, I am not able to modify the \foo command, though I could define a wrapper.

• \foo\space bar maybe? – clemens Jun 27 '15 at 15:26
• Yep, \space is what I needed. – Ruud Jun 27 '15 at 15:33

You want \space instead of \  or instead of the braces. Braces are unexpandable tokens which means they're not removed in \write18. \  is an unexpandable primitive which again means it is not removed (or rather: expanded) in \write18. \space on the other hand is an expandable macro which expands to a space.

\documentclass{article}

\begin{document}

\def\foo{foo}
\edef\test{\foo\ bar}
\show\test

\edef\test{\foo{} bar}
\show\test

\edef\test{\foo\space bar}
\show\test

\end{document}


The log entry:

> \test=macro:
->foo\ bar.
l.7 \show\test

> \test=macro:
->foo{} bar.
l.10 \show\test

> \test=macro:
->foo bar.
l.13 \show\test