22

Is there a way to access environment variables from within a LaTeX document? Suppose I define a variable in a batch file:

set MY_VAR=HelloWorld

How can I programmatically print the string "HelloWorld" inside my LaTeX document, without resorting to creating a new source document with the string in it?

  • Related: http://tex.stackexchange.com/questions/62010/can-i-access-system-environment-variables-from-latex-for-instance-home – Dror Jan 19 '14 at 15:08

2 Answers2

15

You could use the write18 feature. For example:

\documentclass{article}
\immediate\write18{echo $MY_VAR > var.tex}
\begin{document}
\input{var}
\end{document}

Though, a file var.tex would be automatically created. You may have to enable the write18 feature, for instance by compiling with

pdflatex --enable-write18 filename.tex

or configuring your editor accordingly.

I just tested this example with the line

\immediate\write18{kpsewhich -var-value=TEXMFHOME > var.tex}

and got C:/Users/stefan/texmf as output in the pdf file.

Stefan Kottwitz
  • 231,401
13

A LuaTeX solution:

\edef \myvar{%
   \directlua{
     tex.sprint(os.getenv('MY_VAR'))
}}

\myvar
topskip
  • 37,020