1

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202

1 Answers1

2

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:

If the error message is on stderr

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.

If the error message is on stdout

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.

Community
  • 1
  • 1
derobert
  • 49,731
  • 15
  • 94
  • 124
  • The error message is on `stderr` at least but I don't really want want to create tmp files everytime I cat something. I guess I should look into fixing pygmentize and not a work around. – Chris Seymour Jan 03 '13 at 20:12
  • @sudo_O Well, check the 'more complicated' link... you can do that whole sequence of redirects and avoid the temp file. But yeah, really, you should fix the program. And please once you find the fix, submit a patch to Ubuntu so others can benefit, too. – derobert Jan 03 '13 at 21:02