Pregunta

How can I store text in a Bash here document without having to escape special characters? For example, how could I modify the following script in order to preserve the LaTeX code?:

#!/bin/bash

IFS= read -d '' titlePage << "EOF"
\documentclass{article}
\usepackage{graphicx}
\usepackage{fix-cm}
\begin{document}
\pagestyle{empty}
\vspace*{\fill}
\begin{center}
\hrule
\vspace{1.5 cm}
\textbf{
\fontsize{25}{45}\selectfont
The Title\\
of\\
\fontsize{45}{45}\selectfont
\vspace{0.5 cm}
THIS DOCUMENT\\
\vspace{1.5 cm}
\hrule
\vspace{3.5 cm}
}
\end{center}
\vspace*{\fill}
\end{document}
EOF
echo "${titlePage}" >> 0.tex
pdflatex 0.tex
¿Fue útil?

Solución

The problem is not with the here doc, but with the fact that read parses its input. Using read -r should help; or if you really just want the here doc in a file, cat <<'here' >file

Otros consejos

Disclaimer:

  • See @tripleee's answer for the correct and simplest solution.
  • While this answer always worked, it originally contained an incorrect claim. Now it's just an alternative solution.

Since a variable is being assigned to here, another solution is to use a regular - but multiline - single-quoted string literal:

titlePage='\documentclass{article}
\usepackage{graphicx}
\usepackage{fix-cm}
\begin{document}
\pagestyle{empty}
\vspace*{\fill}
\begin{center}
\hrule
\vspace{1.5 cm}
\textbf{
\fontsize{25}{45}\selectfont
The Title\\
of\\
\fontsize{45}{45}\selectfont
\vspace{0.5 cm}
THIS DOCUMENT\\
\vspace{1.5 cm}
\hrule
\vspace{3.5 cm}
}
\end{center}
\vspace*{\fill}
\end{document}'

echo "${titlePage}" >> 0.tex
pdflatex 0.tex

Whitespace matters inside the string:

  • The content starts right after the opening '.
  • Ends by placing the closing ' directly after the last char. - unless you want a terminating \n.
  • The - here-doc option to strip leading tabs (so as to allow indentation for visual clarity) is NOT available with this approach.

For stuff like that, you can also consider sedding it out of the file itself. It also separates your code from the data. (That's why I often use it.)

#!/bin/sh

titlepage=$(sed '1,/^#START-TITLE/d;/^#END-TITLE/,$d' $0)
....
exit 0

#START-TITLE
.....
#END-TITLE

Also consider an indented here doc:

foo <<- \marker
    tab-indented text
    marker

that also gives (some) visual separation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top