我正在编写一个bash脚本,遇到了一个问题。 我使用普通的if / fi语句来推动我所知道的,并尝试使用它们来设置与拾取操作系统版本相关的variables,如RH 7,Debian 7,Ubuntu等。我遇到的问题是它只是不像我想的那样工作。 我用手运行每个部分,它工作得很好,但是当我把所有东西放在一个脚本中,什么都没有。
有一个更好的方法吗? 先谢谢你
value1=$(cat /etc/redhat-release | awk '{ print $4 }' | cut -c 1) value2=$(cat /etc/redhat-release | awk '{ print $3 }' | cut -c 1) value3=$(lsb_release -sr) value4=$(cat /etc/debian_version) if [[ $value1 -eq 7 ]] && [[ -e /etc/redhat-release ]]; then OS=RedHat VER=RH7 elif [[ $value2 -eq 6 ]] && [[ -e /etc/redhat-release ]]; then OS=RedHat VER=RH6 elif [[ $value3 = 14.04 ]]; then OS=Ubuntu VER=UB1404 elif [[ -e /etc/debian_version ]] && [[ $value4 -eq 7 ]]; then OS=Debian VER=DEB7 fi
我认为你的问题可能是浮点数和string比较的一些问题。
AFAIK,testing不能处理浮点值,所以你的$value3 = 14.04testing会给你一个syntax error: invalid arithmetic operator (error token is ".04") 。
你可以像这样把数字看作string:
elif [[ "$value3" == "14.04" ]]; then
还要注意$value3附近的引号,这也是把我在7.8的debian中返回的7.8作为string处理的必要条件。
如果您只想比较主版本号,也可以在点之后剥离零件:
value3=$(lsb_release -sr | cut -d. -f1)
这将拆分由lsb_release -sr返回的string. 我们用-d.定义了分隔符-d. 参数,然后用-f1select结果的第一列。
这也适用于value4:
value4=$(cat /etc/debian_version | cut -d. -f1)
这削减了我的/etc/debian_version 7.8之前和7在添加cut后的输出。
您也可能想要禁止不存在的文件的警告。 我没有可用的redhat系统,所以我将来自前2个命令的错误消息redirect到/dev/null如下所示:
value1=$(cat /etc/redhat-release 2> /dev/null | awk '{ print $4 }' | cut -c 1 )
让我知道如果你需要任何其他帮助。 另外请添加一些输出,甚至可能期望您的脚本输出,所以我们可以看到你的问题在哪里。