V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sudoy
V2EX  ›  问与答

bash 判断 Ubuntu 版本是否大于 18.04

  •  
  •   sudoy · 2021-03-02 13:15:53 +08:00 · 990 次点击
    这是一个创建于 1144 天前的主题,其中的信息可能已经有所发展或是发生改变。

    就是想通过 .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
    
    第 1 条附言  ·  2021-03-02 13:52:55 +08:00

    感谢 @@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 条回复    2021-03-02 13:52:33 +08:00
    love
        1
    love  
       2021-03-02 13:30:00 +08:00
    python -c "print($VER > 18.04)" | grep True && {
    echo OK
    }
    Xusually
        2
    Xusually  
       2021-03-02 13:34:34 +08:00   ❤️ 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  
       2021-03-02 13:35:06 +08:00
    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  
       2021-03-02 13:35:09 +08:00
    # lsb_release --release
    Release: 20.04
    sudoy
        5
    sudoy  
    OP
       2021-03-02 13:50:04 +08:00
    @Xusually 感谢!我测试了这个方案可行的!
    sudoy
        6
    sudoy  
    OP
       2021-03-02 13:50:10 +08:00
    @love @miscnote 两位这个方法好像是要依赖于 python 和 perl,我想要纯 bash 脚本的
    taolu
        7
    taolu  
       2021-03-02 13:52:33 +08:00   ❤️ 1
    test $(echo "$VER > 18.04" | bc) -eq 1 && echo "Ubuntu version is greater than 18" || echo "Ubuntu version is less than 18"
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   936 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:19 · PVG 06:19 · LAX 15:19 · JFK 18:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.