Detect python version in shell script

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

    Here is another solution using hash to verify if python is installed and sed to extract the first two major numbers of the version and compare if the minimum version is installed

    if ! hash python; then
        echo "python is not installed"
        exit 1
    fi
    
    ver=$(python -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/')
    if [ "$ver" -lt "27" ]; then
        echo "This script requires python 2.7 or greater"
        exit 1
    fi
    

提交回复
热议问题