# How to execute a command only on the next run?

Let's say I have a command \foo that I want to execute only on the next run of TeX. How do I create a command \onceFoo that does this? (It is also permitted to execute \foo if the aux file has been compromised.)

Minimal (non-)working example:

\documentclass{article}
\def\foo{First execution}
\def\onceFoo{This doesn't work.}
\begin{document}
testing: \onceFoo
\end{document}


The desired output is

testing: First execution


on the first run of latex, and

testing:


on every subsequent run.

If the file above (with the correct definition of \onceFoo) has been run several times, and the line new testing: \onceFoo is added, then the desired output is

testing: new testing: First execution


on the first subsequent run, and

testing: new testing:


on all runs thereafter.

Motivation: I would like to create a command that clears certain useful files and recomputes them. Normally, this command should be used for a single run to remove corrupted information (or for testing); afterwards, the command should be removed from the source file. However, some users (notably I) are likely to forget to remove the command, since it does not actually break anything--it only produces a significant drop in efficiency, because many things must be recalculated. Thus, I would like a second version of this command that affects only the first run after it is added.

-

\documentclass{article}
\def\foo{First execution}
\newif\ifFirstRun
\makeatletter
\AtBeginDocument{%
\ifx\FirstRunTest\@undefined
\FirstRuntrue
\else
\FirstRunfalse
\fi
\write\@auxout{\string\gdef\string\FirstRunTest{}}}

\makeatother
\begin{document}
testing: \ifFirstRun\foo\fi
\end{document}


And the same for counting the runs:

\documentclass{minimal}
\def\foo{First execution}
\makeatletter
\AtBeginDocument{%
\ifx\runNo\@undefined
\newcount\runNo \runNo=1
\else