Detect python version in shell script

前端 未结 14 2135
清歌不尽
清歌不尽 2020-12-07 20:26

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

14条回答
  •  余生分开走
    2020-12-07 21:10

    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
    

提交回复
热议问题