sudoy
V2EX  ›  问与答

bash 判断 Ubuntu 版本是否大于 18.04

  •  
  •   sudoy · Mar 2, 2021 · 1522 views
    This topic created in 1912 days ago, the information mentioned may be changed or developed.

    就是想通过 .sh 文件判断 Ubuntu 版本是否高于 18.04 。搜了半天没找到合适的,下面这个还是错的。哪位大佬帮忙改下

    VER=$(lsb_release --release | cut -f2)
    
    if [ "$VER > 18.04" | bc ]; then
            echo "Ubuntu version is greater than 18"
    else
            echo "Ubuntu version is less than 18"
    exit 0
    fi
    
    Supplement 1  ·  Mar 2, 2021

    感谢 @@Xusually 的解决方案,亲测可行,代码如下:

    # Check if Ubuntu version is greater than 18.04
    echo "Checking Ubuntu version..."
    VER=$(lsb_release --release | cut -f2)
    function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }
    
    if [ $(version $VER) -ge $(version "18.04") ]; then
            echo "Ubuntu version is greater than 18.04"
    else
            echo "Ubuntu version is less than 18.04"
    exit 0
    fi
    
    
    7 replies    2021-03-02 13:52:33 +08:00
    love
        1
    love  
       Mar 2, 2021
    python -c "print($VER > 18.04)" | grep True && {
    echo OK
    }
    Xusually
        2
    Xusually  
       Mar 2, 2021   ❤️ 1
    #cat ver.sh

    function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }

    VER=$(lsb_release --release | cut -f2)

    if [ $(version $VER) -ge $(version "18.04") ]; then
    echo "Ubuntu version is greater than 18"
    else
    echo "Ubuntu version is less than 18"
    fi

    # chmod +x ver.sh
    # ./ver.sh
    Ubuntu version is greater than 18
    miscnote
        3
    miscnote  
       Mar 2, 2021
    just my way:
    perl -e 'open $fd,"/etc/issue";$str=<$fd>;($ver)=$str=~/(\d+\.\d+\.\d+)/;print "true" if $ver>18.04'
    Xusually
        4
    Xusually  
       Mar 2, 2021
    # lsb_release --release
    Release: 20.04
    sudoy
        5
    sudoy  
    OP
       Mar 2, 2021
    @Xusually 感谢!我测试了这个方案可行的!
    sudoy
        6
    sudoy  
    OP
       Mar 2, 2021
    @love @miscnote 两位这个方法好像是要依赖于 python 和 perl,我想要纯 bash 脚本的
    taolu
        7
    taolu  
       Mar 2, 2021   ❤️ 1
    test $(echo "$VER > 18.04" | bc) -eq 1 && echo "Ubuntu version is greater than 18" || echo "Ubuntu version is less than 18"
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5591 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 148ms · UTC 01:47 · PVG 09:47 · LAX 18:47 · JFK 21:47
    ♥ Do have faith in what you're doing.