linux - Bash 脚本字符串比较运算符

标签 linux bash

我想这是一个由两部分组成的问题。我正在尝试编写 if 语句,其值是从网站上提取的并且是字符串。但是我希望它们是整数,这样我就可以对它们进行整数比较。但就将值转换为整数而言,我在网上找到的信息基本上没有产生任何结果。我留下了这段代码,如果我使用“>=”会产生错误,而只使用“=”则不会出错。那么有没有办法将字符串转换为int呢?如果不是,我如何编写它才能无错误地执行,为什么我会收到当前构造的错误?

 #!/bin/bash

    webpage=$(curl http://w1.weather.gov/xml/current_obs/KPNE.xml | grep 'visibility_mi>')
    webpage2=$(curl http://w1.weather.gov/xml/current_obs/KPNE.xml | grep '<weather>')

    #Test code:
    #echo $webpage
    #echo $webpage2

        extrct=${webpage%</*}
        extrct=${extrct##*>}

        extrct2=${webpage2%</*}
        extrct2=${extrct2##*>}

        echo -en '\n'
        echo ===============================================
        echo Output Variables Values testing purposes:
        echo $extrct   
        echo $extrct2 
        echo ===============================================  
        echo -en '\n'          

            if [[ $extrct2 == 'Rain' ]]
            then 
                echo 'Rain!'
            elif [[ $extrct2 == 'Snow' ]]
            then
                echo 'Snow!'

                elif [ $extrct >= '7' ]
                then
                    echo 'All Clear!'
                elif [ $extrct >= '4' and < '7' ]
                then
                    echo 'Limited Visibility'
                elif [ $extrct < '4' ]
                then
                    echo 'Very Low Visibility!'
            fi


    read 

最佳答案

在 bash 中,要将变量作为整数进行比较,您必须使用不同的比较运算符。这里有一些:

  • -gt = 大于
  • -ge = 大于或等于
  • -eq等于

参见 http://tldp.org/LDP/abs/html/comparison-ops.html用于更多运算符。请注意,所有变量仍存储为字符串。

编辑:这是一个固定的 if 语句:

            elif [ $((extrct)) -ge 7 ]
            then
                echo 'All Clear!'
            elif [ $((extrct)) -ge 4 -a $((extrct)) -lt 7 ]
            then
                echo 'Limited Visibility'
            elif [ $((extrct)) -lt 4 ]
            then
                echo 'Very Low Visibility!'
        fi

关于linux - Bash 脚本字符串比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643324/

相关文章:

bash - 是否可以在使用原始脚本的同时运行重复的 bash 脚本?

linux - 配置logrotate状态文件

linux - Fedora13安装meego sdk 1.2失败

linux - 自定义 bash 命令在终端中有效但在脚本中无效

linux - 在 Linux 中通过脚本安装应用程序

python - 从 bash 脚本执行带有 "import requests"的 python 脚本

linux - 如何用 bash 脚本匹配 "whitespace"和 "OR"条件?

bash 提示 shell 在终端和 tty 控制台中显示不同

linux - Linux 延迟过多

linux - 查找目录/子目录的大小