## 2011-11-07

### Customize LaTeX output from a shell (Unix)

This post explains how to influence LaTeX output via a Unix shell, including the insertion of a word that you pass to a script. It is partially based on an answer given by Will Robertson on StackOverflow.

### Custom command from shell, fallback if missing

Call PDFLaTeX as follows
    pdflatex "\newcommand\comment[1]{\textbf{#1}}\input{myfile}"

The the LaTeX code, you can use the following meta-command to define a fallback (to be used when you invoke pdflatex directly on the file):
    \providecommand{\comment}[1]{\emph{#1}}% fallback definition


### Boolean flag from shell

Define a symbol from the shell:
    pdflatex "\def\myflag{}\input{myfile}"

Now you can check for the “definedness” of this symbol in your LaTeX code.
    \ifdefined\myflag
\newcommand\comment[1]{\emph{#1}}
\else
\newcommand\comment[1]{\textbf{#1}}
\fi

It thus works as a boolean flag: When you invoke PDFLaTeX like above, the flag is on, when you directly compile the file, the flag is off.

### Example: Hide the solutions to exercises

Let’s say you want to write an an exercise sheet with solutions. When you compile the LaTeX document normally, the solutions should be shown. This is how you typeset the document while creating it. What you initially hand out to students, though, is a sheet without solutions. Then you switch on a flag as shown above:
    pdflatex "\def\hideSolution{}\input{myfile}"

In the LaTeX document, you use package comment to create a new environment that can be either hidden (excluded) or shown (included):
    \usepackage{comment}
\ifdefined\hideSolution
\excludecomment{solution}
\else
\includecomment{solution}
\fi

In use, the solution environment looks as follows.
    Question: What is the solution?
\begin{solution}
The solution is: maybe.
\end{solution}

Warning: There must not be any spaces before or after \begin{solution} and \end{solution}. Otherwise, comment will throw an error.

### Example: Personalize a document

In order to personalize a document, we want to insert a name that we specify via a shell:
    $../personalize.sh "Jane Doe"  personalize.sh simply inserts$1, the first argument, into LaTeX code.
    #!/bin/bash
# This file can be anywhere but must be executed in the directory of mydoc.tex
pdflatex "\newcommand\personalize{\$1}\input{mydoc}"

The following is an excerpt from the LaTeX document:
    \begin{document}

% \personalize is defined via tools/personalize.sh
\ifdefined\personalize
\makeatletter
\renewcommand{\@oddfoot}{\hfill\fbox{Personal copy of \personalize}}
\makeatother
\fi

\maketitle

If the personalization name is defined, we insert it into the footer on odd pages.

### More ideas

This technique is useful whenever a document has several versions. For example, you could also configure from a shell whether or not slides are typeset as a handout or not.