Detect python version in shell script

前端 未结 14 2119
清歌不尽
清歌不尽 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 20:58

    If you need to check if version is at least 'some version', then I prefer solution which doesn't make assumptions about number of digits in version parts.

    VERSION=$(python -V 2>&1 | cut -d\  -f 2) # python 2 prints version to stderr
    VERSION=(${VERSION//./ }) # make an version parts array 
    if [[ ${VERSION[0]} -lt 3 ]] || [[ ${VERSION[0]} -eq 3 && ${VERSION[1] -lt 5 ]] ; then
        echo "Python 3.5+ needed!" 1>&2
        return 1
    fi
    

    This would work even with numbering like 2.12.32 or 3.12.0, etc. Inspired by this answer.

提交回复
热议问题