[Tex/LaTex] How to check in LaTeX (or plain TeX) whether a command exists, by name

conditionalsmacros

I'm looking for a LaTeX way to control macro expansion, contingent on some macro being defined or not. I'm looking for something like this (but then actually working):

\newcommand[1]{\checkfor}{
  \if\isdef\csname{#1}
  ... expand this if command exists ...
  \else
  ... expand this if command does not exist ...
  \fi
}

which can then be called using

\checkfor{CommandName}

(this example is, of course, useless. The actual code I want to use this kind of expansion in is a package that dynamically creates a large number of macros from an even larger set of possible macros, with default behaviour for "all macros". Since not "all" macros may exist, I need some way to test whether a macro was declared, before I can expand based on its value).

Best Answer

Is this what you are looking for:

\documentclass[12pt]{article}

\newcommand{\checkfor}[1]{%
  \ifcsname#1\endcsname%
    ... command '#1' exists ...%
  \else%
    ... command '#1' does not exist ...%
  \fi%
}

\begin{document}
\checkfor{CommandName}\par
\checkfor{section}
\end{document}
Related Question