Comparing PHP version numbers using Bash?

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

    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).

提交回复
热议问题