Bash – Ignore escape characters when printing string in shell script

bashquotingshell-script

I just wrote a simple shell script to save a LaTeX expression as a PNG file. It works fine, except for the LaTeX-syntax for "next row", i.e. the double backslash \\.

When for instance my input expression is like this:

\left( \begin{array}{cc}1 & 2\\ 3 & 4\end{array} \right)

The double backslash is reduced to a single one. I know I can add more backslashes in my expression, but I want those expressions to be genuine LaTeX, not some weird LaTeX-bash combination.

My script:

#!/bin/bash

if [ $# -ne 2 ]; then
    echo -e "Er moeten twee argumenten worden opgegeven:\n(1) LaTeX code\n(2) Bestandsnaam zonder extensie"
else
    SaveDir="/home/pieter"
    echo "\documentclass{article}\usepackage[utf8x]{inputenc}\pagestyle{empty}\begin{document}\[ $1 \]\end{document}" > /tmp/$2.tex
    latex -output-directory /tmp -interaction=batchmode $2.tex
    dvips -o /tmp/$2.ps -E /tmp/$2.dvi
    convert -units PixelsPerInch -density 200 /tmp/$2.ps -trim $SaveDir/$2.png
fi

So, how can I ignore the escape characters and literally print my LaTeX expression? Preferably without using sed.

Best Answer

If the TeX you want to output is fixed in your script, the safest is to use something like this:

cat > $2.tex << 'ENDHEADER'
\documentclass{article}
 \usepackage[utf8x]{inputenc}
 \pagestyle{empty}
\begin{document}
\[
ENDHEADER
echo $1 >> $2.tex
cat >> $2.tex << 'ENDFOOTER'
\]
\end{document}
ENDFOOTER

The data between the cat and END markers will be output as is with no substitutions. (I'm assuming all the newlines added are ok.)

Make sure you use hard quotes (') when you pass your TeX as an argument:

./your_script '\left( \begin{array}{cc}1 & 2\\ 3 & 4\end{array} \right)'
Related Question