Insert Bash code with coloration into my latex report

Not contradicting anything in JoG's answer:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,
  showstringspaces=false,
  commentstyle=\color{red},
  keywordstyle=\color{blue}
}

\begin{document}

\begin{lstlisting}[language=Java,caption={Java version}]
public class HelloWorld {
   // Here's the main class
   public static void main(String[] args) {
       System.out.println("Hello, world!");
   }
}
\end{lstlisting}

\begin{lstlisting}[language=bash,caption={bash version}]
#!/bin/bash
echo "Hello, world!"
\end{lstlisting}

\end{document}

enter image description here


listings does not work well for shell code because it can not deal well with a lot of codes such as the following one:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,
  showstringspaces=false,
  commentstyle=\color{red},
  keywordstyle=\color{blue}
}
\begin{document}
\begin{lstlisting}[language=bash,caption={bash version}]
#!/bin/bash
echo the $# parameter destroys listings syntax highlighting
\end{lstlisting}
\end{document}

enter image description here

It does not produce what you could expect (the # sign is considered as a comment delimiter and thus the rest of the line is not colored as it should.

For bash you may instead use the minted package which need an exterior tool to produce the highlighting (the pygments python library).

Compare the previous result with the one produced by this code (you need to call the compiler with pdflatex -shell-escape myfile.tex):

\documentclass{article}

\usepackage{minted}

\begin{document}

\begin{minted}{bash}
#!/bin/bash
echo the $# parameter did not destroy pygments syntax highlighting
\end{minted}

\end{document}

enter image description here


for java i use the listings package with following style:

\definecolor{javakeyword}{rgb}{0,0,0.5}
\definecolor{javastring}{rgb}{0,0.5,0}
\definecolor{javacomment}{rgb}{0.5,0.5,0.5}
\lstdefinestyle{java}{
   language=Java,
   showspaces=false,
   showstringspaces=false,
   basicstyle=\ttfamily,
   columns=flexible,
   stringstyle=\color{javastring},
   keywordstyle=\color{javakeyword}\ttfamily\textbf,
   commentstyle=\color{javacomment}\ttfamily\textit
 }

which i then use like

\begin{lstlisting}[float,style=Java,caption={Correct Logging example},label=lst:logging]
  private static final Log log = LogFactory.getLog(MyClass.class);

  public void doSomeStuff(Stuff stuff) throws StuffException {
      checkNotNull(stuff,"stuff should not be null");
  }
\end{listlisting}

Tags:

Code