Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 441
KaiserJohaan Avatar asked Nov 09 '12 14:11

KaiserJohaan


People also ask

Which version of Python do I have?

If you have Python installed then the easiest way you can check the version number is by typing "python" in your command prompt. It will show you the version number and if it is running on 32 bit or 64 bit and some other information. For some applications you would want to have a latest version and sometimes not.

How can I check all the installed Python versions on Linux?

You can query by Python Version: python3 --version //to check which version of python3 is installed on your computer python2 --version // to check which version of python2 is installed on your computer python --version // it shows your default Python installed version.

How do I check my Python version in putty?

The sys module that is available in all Python versions provides system-specific parameters and functions. sys. version_info allows you to determine the Python version installed on the system. It returns a tuple that contains the five version numbers: major , minor , micro , releaselevel , and serial .


2 Answers

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.

like image 134
Alfe Avatar answered Sep 19 '22 12:09

Alfe


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
like image 22
xmonk Avatar answered Sep 18 '22 12:09

xmonk