# Running new command only if it exists

How do I get LaTeX to run a command only if it exists? I need something like:

\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
% \newcommand{\mytitle}{Title Test}
\begin{document}
\if mytitle exists
\mytitle %true
\else
do not run the command
\fi
\end{document}


To prevent the error message appears: 'Undefined control sequence \mytitle' I need to decide this because I will use Boolean operation on multiple files.

-

I usually use \ifdefined:

\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
%\newcommand{\mytitle}{ducks}
\begin{document}

\ifdefined\mytitle
Yay, \mytitle!
\else
Oops.
\fi
\end{document}


As Martin Scharrer mentioned in the comment, \ifdefined is part of the e-TeX extension.

-
Note that \ifdefined is part of the e-TeX extension, which is part of any modern LaTeX compiler. –  Martin Scharrer Sep 16 '11 at 14:18
Thanks @Martin, I'll add that to my answer. =) –  Paulo Cereda Sep 16 '11 at 14:20
Thank you Paulo Cereda. Andrey Vihrov i dont undestand you. –  Regis da Silva Sep 16 '11 at 14:24

There is the kernel command \@ifundefined:

\makeatletter
\@ifundefined{mytitle}{do not run the command}{\mytitle}
\makeatother


\ifdefined\mytitle
\mytitle
\else
do not run the command
\fi


The two will give different result in case

\let\mytitle\relax


has been given before the test, because \@ifundefined tests whether the control sequence name given as argument is equivalent to \relax. There are TeXnical reasons for this.

-
Very useful explanation of the difference between \ifdefined and (negative of) \@ifundefined! –  Mico Sep 16 '11 at 18:41

An alternative way is to use \providecommand to define a command that does nothing. This will only define the command if it is not already defined. If it is already defined, the original definition is not altered. This eliminates the need to test it every time you want to use it.

\documentclass{article}
\begin{document}

\providecommand{\mytitle}{}%

This does nothing: \mytitle
\end{document}


If the command is expected to take a parameter you can do something like:

\providecommand{\mytitle}[1]{#1}%


which will just return the parameter, and hence do nothing with it.

-
Thank you all enormously. –  Regis da Silva Sep 16 '11 at 15:37

You can use \csname … \endcsname for that. \csname … \endcsname constructs a control sequence with the given name. If the control sequence does not exist, it is temporarily let equal to \relax, which does nothing.

So,

\csname mytitle\endcsname


will work both when \mytitle is and is not defined.

If your command takes parameters, this simple method can't be used anymore. Then you can use the \@ifundefined command:

\makeatletter
\@ifundefined{mytitle}{not defined}{defined}
\makeatother

-