I have the following script ~/bin/cat
that uses pygmentize
to display syntax highlightable files when ever possible if not just regular old cat
.
#!/bin/bash
for var; do
pygmentize "$var" 2> /dev/null
if [ $? -ne 0 ]; then
/bin/cat "$var"
fi
done
This works fine on my work machine but not on my home machine. At home if pygmentize
doesn't recognize a file it displays the same error message but the exit status is 0 where as at work it returns 1, which breaks the script. The only difference being at work I run Fedora and at home Ubuntu.
$ pygmentize testfile
Error: no lexer for filename 'testfile' found
$ echo $?
0
$ file testfile
file: ASCII text
This is strange as both are the same version
$ pygmentize -V
Pygments version 1.4, (c) 2006-2008 by Georg Brandl.
I could grep
for Error
in stderr
but how do I do this without throwing away stdout
, How should I handle this?
Well, your best approach is to fix pygmentize
to properly return an error code. As Ignacio Vazquez-Abrams mentions, one of the distros has a patch that is either causing or fixing this.
But, here is how to work around it:
The easiest way is probably to redirect stderr to a temporary file, and leave stdout alone:
pygmentize "$var" 2> "$tmpfile"
then you can grep "$tmpfile"
. There are other ways, but they're more complicated.
Yep, that'd be another bug in pygmentize, it should be on stderr. The temporary file will work again, however. Just cat
the temporary file back to stdout if its OK. Alternatively, you can use tee
to duplicate the stdout to several destinations.