# Problem using \write18 in beamer frame

I am stuck in front of this little but annoying problem. I am trying to use a \write18 command in which I use a local variable \mytest. I really don't understand why this SWE works if I comment the two \begin{frame} and \end{frame} and doesn't if I use them. Also, it works if I use \jobname in place of \mytest in the \write18 statement.

Does anybody can has an idea ?

\documentclass{beamer}

\makeatletter
\newcommand{\print}[1]{
\def\mytest{#1}
\mytest
\write18{echo;echo my test is \mytest\   }
}
\makeatother

\begin{document}
\begin{frame}{}
\print{hello world}
\end{frame}

\end{document}


\write18 is executed at shipout time, when the frame has already ended, so the local definition of \mytest has been discarded.
If you use \immediate\write18 you get what you want. Of course, the instruction will be executed as many times as there are overlays in the frame, so perhaps an \only instruction should be used.