Detect python version in shell script

前端 未结 14 2096
清歌不尽
清歌不尽 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:07

    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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题