문제

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:

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top