Comparing PHP version numbers using Bash?

前端 未结 10 961
余生分开走
余生分开走 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:59

    Here's another solution that:

    • does not run any external command apart from tr
    • has no restriction on number of parts in version string
    • can compare version strings with different number of parts

    Note that it's Bash code using array variables.

    compare_versions()
    {
        local v1=( $(echo "$1" | tr '.' ' ') )
        local v2=( $(echo "$2" | tr '.' ' ') )
        local len="$(max "${#v1[*]}" "${#v2[*]}")"
        for ((i=0; i<len; i++))
        do
            [ "${v1[i]:-0}" -gt "${v2[i]:-0}" ] && return 1
            [ "${v1[i]:-0}" -lt "${v2[i]:-0}" ] && return 2
        done
        return 0
    }
    

    The function returns:

    • 0 if versions are equal (btw: 1.2 == 1.2.0)
    • 1 if the 1st version is bigger / newer
    • 2 if the 2nd version is bigger / newer

    However #1 -- it requires one additional function (but function min is quite usable to have anyway):

    min()
    {
        local m="$1"
        for n in "$@"
        do
            [ "$n" -lt "$m" ] && m="$n"
        done
        echo "$m"
    }
    

    However #2 -- it cannot compare version strings with alpha-numeric parts (though that would not be difficult to add, actually).

    0 讨论(0)
  • 2020-12-02 13:59

    If you're on Bash 3 with an older version of sort (lookin at you macOS...), then I created the following helper script you can source in (can also be ran as a command):

    https://github.com/unicorn-fail/version_compare

    0 讨论(0)
  • 2020-12-02 14:05

    A much safer option for testing the PHP CLI version is to use PHP's own version_compare function.

    #!/bin/bash
    
    MIN_VERSION="7.0.0"
    MAX_VERSION="7.1.4"
    PHP_VERSION=`php -r 'echo PHP_VERSION;'`
    
    function version_compare() {
        COMPARE_OP=$1;
        TEST_VERSION=$2;
        RESULT=$(php -r 'echo version_compare(PHP_VERSION, "'${TEST_VERSION}'", "'${COMPARE_OP}'") ? "TRUE" : "";')
    
        test -n "${RESULT}";
    }
    
    if ( version_compare "<" "${MIN_VERSION}" || version_compare ">" "${MAX_VERSION}" ); then
        echo "PHP Version ${PHP_VERSION} must be between ${MIN_VERSION} - ${MAX_VERSION}";
        exit 1;
    fi
    
    echo "PHP Version ${PHP_VERSION} is good!";
    
    0 讨论(0)
  • 2020-12-02 14:06
    v_min="5.2.15"
    v_max="5.3.15"
    v_php="$(php -v | head -1 | awk '{print $2}')"
    
    [ ! "$v_php" = "$(echo -e "$v_php\n$v_min\n$v_max" | sort -V | head -2 | tail -1)" ] && {
      echo "PHP Version $v_php must be between $v_min - $v_max"
      exit
    }
    

    This puts v_min, v_max and v_php in version order and tests if v_php is not in the middle.

    0 讨论(0)
提交回复
热议问题