I will assume that by shell you mean a Unix shell such as bash. You may want to look at the "here document" feature of bash. The simplest you can do is
#!/bin/bash
latex <<theend
\documentclass{article}
\begin{document}
Blah blah
\end{document}
theend
echo "Done!"
however this may lead to some problems if the latex processing needs multiple passes. It will also clutter your current directory with bunch of extra files produced by latex, such as log file, .aux file, etc., which may not be what you want.
A better option is to create a temporary directory, extract the LaTeX document into it using cat and to run LaTeX with this document as input. You may want to run LaTeX several times to make sure all cross references are resolved. At the end you just copy the generated .dvi or .pdf file back to your current directory.
An example of such script is below. It uses mktemp to create a temporary directory. As far as I know, mktemp is not available on every Unix, but it should be available on every system that has GNU coreutils.
There are probably better ways how to handle pretty much every step of the process, but this should get you started.
#!/bin/bash
# Create a temporary directory
curdir=$( pwd )
tmpdir=$( mktemp -dt "latex.XXXXXXXX" )
# Set up a trap to clean up and return back when the script ends
# for some reason
clean_up () {
cd "$curdir"
[ -d "$tmpdir" ] && rm -rf "$tmpdir"
exit
}
trap 'clean_up' EXIT SIGHUP SIGINT SIGQUIT SIGTERM
# Switch to the temp. directory and extract the .tex file
cd $tmpdir
# Quoting the 'THEEND' string prevents $-expansion.
cat > myfile.tex <<'THEEND'
\documentclass{article}
\begin{document}
Blah blah \(x^2 + 1\) or $x^2 + 1$.
\end{document}
THEEND
# If the file extracts succesfully, try to run pdflatex 3 times.
# If something fails, print a warning and exit
if [[ -f 'myfile.tex' ]]
then
for i in {1..3}
do
if pdflatex myfile.tex
then
echo "Pdflatex run $i finished."
else
echo "Pdflatex run $i failed."
exit 2
fi
done
else
echo "Error extracting .tex file"
exit 1
fi
# Copy the resulting .pdf file to original directory and exit
cp myfile.pdf $curdir
exit 0
catline of code to help deal with the potential problem you mentioned. – lawlist Mar 11 '13 at 16:32\\\$instead. But I am not editting the answer again, because there is probably something else that will have to be escaped, and this will never end :) – Jan Hlavacek Mar 12 '13 at 14:02latexmk -c, and it is a workaround to the inability of TeXLive on OSX to use theaux_dirandaux-directoryoptions. – lawlist Mar 12 '13 at 16:15verbatimin LaTeX), and now (thanks to Jan Hlavacek), I understand that it is the usage of the'before and afterTHEENDthat avoids problems with the $ sign within the LaTeX code. – lawlist Mar 12 '13 at 18:27sharformat, and hack the LaTeXing into it. – vonbrand Mar 12 '13 at 18:27