Comparing PHP version numbers using Bash?

前端 未结 10 1083
余生分开走
余生分开走 2020-12-02 13:30

I have this script that should make sure that the users current PHP version is between a certain range, though it SHOULD work, there is a bug somewhere that makes it think t

10条回答
  •  执念已碎
    2020-12-02 13:55

    I wrote this inelegant function a while back for a similar problem. vers_limit will return 0 if arg1 is less than or equal to arg2, non-0 otherwise:

    vers_limit()
    {
    VERNEW=$1
    VERLMT=$2
    
    CHKNEW=$VERNEW
    CHKLMT=$VERLMT
    
    PASSED=
    
    while :
    do
            PARTNEW=${CHKNEW%%.*}
            PARTLMT=${CHKLMT%%.*}
            if [[ $PARTNEW -lt $PARTLMT ]]
            then
                    PASSED=GOOD
                    break
            elif [[ $PARTNEW -gt $PARTLMT ]]
            then
                    PASSED=
                    break
            else
                    NXTNEW=${CHKNEW#*.}
                    if [[ $NXTNEW == $CHKNEW ]]
                    then
                            if [[ $NXTNEW == $CHKLMT ]]
                            then
                                    PASSED=GOOD
                                    break
                            else
                                    NXTNEW=0
                            fi
                    fi
                    NXTLMT=${CHKLMT#*.}
                    if [[ $NXTLMT == $CHKLMT ]]
                    then
                            NXTLMT=0
                    fi
            fi
            CHKNEW=$NXTNEW
            CHKLMT=$NXTLMT
    done
    test "$PASSED"
    }
    

    This is not as compact as some of the other solutions here, nor does it provide 3-way status (i.e., less, equal, greater), though I believe one can order the arguments, interpret the pass/fail status, and/or call twice to accomplish any desired result. That said, vers_limit does have certain virtues:

    1. No calls to external utilities such as sort, awk, gawk, tr, etc.

    2. Handles numeric versions of arbitrary size (up to the shell's limit for integer calculations)

    3. Handles an arbitrary number of "dotted" parts.

提交回复
热议问题