Detect python version in shell script

Solution 1:

You could use something along the following lines:

$ python -c 'import sys; print(sys.version_info[:])'
(2, 6, 5, 'final', 0)

The tuple is documented here. You can expand the Python code above to format the version number in a manner that would suit your requirements, or indeed to perform checks on it.

You'll need to check $? in your script to handle the case where python is not found.

P.S. I am using the slightly odd syntax to ensure compatibility with both Python 2.x and 3.x.

Solution 2:

python -c 'import sys; print sys.version_info'

or, human-readable:

python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'

Solution 3:

You can use this too:

pyv="$(python -V 2>&1)"
echo "$pyv"

Solution 4:

I used Jahid's answer along with Extract version number from a string to make something written purely in shell. It also only returns a version number, and not the word "Python". If the string is empty, Python is not installed.

version=$(python -V 2>&1 | grep -Po '(?<=Python )(.+)')
if [[ -z "$version" ]]
then
    echo "No Python!" 
fi

And let's say you want to compare the version number to see if you're using an up to date version of Python, use the following to remove the periods in the version number. Then you can compare versions using integer operators like, "I want Python version greater than 2.7.0 and less than 3.0.0". Reference: ${var//Pattern/Replacement} in http://tldp.org/LDP/abs/html/parameter-substitution.html

parsedVersion=$(echo "${version//./}")
if [[ "$parsedVersion" -lt "300" && "$parsedVersion" -gt "270" ]]
then 
    echo "Valid version"
else
    echo "Invalid version"
fi