6

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

1
  • Could you clairify what os and shell you're using? I tried it under OS X with bash and zsh, works fine. Commented Nov 9, 2012 at 14:53

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

The reason why it doesn't work is because the result stored in $PYTHON_VERSION is not an integer, so your equality test is being done with two different types.

You can change the if to:

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

or you can just do:

if [ $PYTHON_VERSION = 0 ]; then

2 Comments

ok, I thought bash would convert between string-to-int and int-to-string implicitly?
It does, the problem is not with the conversion but how -eq is interpreting the expression. There are some cases you need to have: if [[ ]] instead of if [ ], or -eq wont do the right thing.
0

here is a possible solution

if sys.version_info < (3, 0):
    reload(sys)
    sys.setdefaultencoding('utf8')
else:
    raw_input = input

this is from an example I had from sleekxmpp, but it does what you need I believe.

1 Comment

Isn't his problem on the shell side?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.