shell scripting checking python version

I have the following shell script to query the python version. It gives me an error stating "Integer expression expected" on the if-statement.

#!/bin/bash


PYTHON_VERSION=`python -c 'import sys; print("%i" % (sys.hexversion<0x03000000))'`

echo $PYTHON_VERSION

if [ $PYTHON_VERSION -eq 0 ]
then
    echo "fine!"
fi

‘echo $PYTHON_VERSION’ prints out ‘0’, so why dosn’t the if-statement work?

EDIT: I am using Windows and Cygwin

Best answer

Good question. For me it’s working fine. You always should quote evaluated variables ("$X" instead of $X); maybe that fixes your error.

But I propose to use the result of the python script instead of its output:

#!/bin/bash
if python -c 'import sys; sys.exit(1 if sys.hexversion<0x03000000 else 0)'
then
    echo "Fine!"
fi

If you like to stay in the shell completely, you also can use the --version option:

case "$(python --version 2>&1)" in
    *" 3."*)
        echo "Fine!"
        ;;
    *)
        echo "Wrong Python version!"
        ;;
esac

Maybe that’s more readable.