I\'d like to detect if python is installed on a Linux system and if it is, which python version is installed.
How can I do it? Is there something more graceful than
Detection of python version 2+ or 3+ in a shell script:
# !/bin/bash
ver=$(python -c"import sys; print(sys.version_info.major)")
if [ $ver -eq 2 ]; then
echo "python version 2"
elif [ $ver -eq 3 ]; then
echo "python version 3"
else
echo "Unknown python version: $ver"
fi
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