帮助比较声明

时间:2013-07-10 13:04:17

标签: shell if-statement

我正在尝试检查工作站的OS X版本,如果它是10.7或更高,请执行此操作。另一方面,如果它在10.7之前做其他事情。你们能否指出我为什么收到下面的错误信息?

非常感谢!

#!/bin/sh

cutOffOS=10.7
osString=$(sw_vers -productVersion)
echo $osString
current=${osString:0:4}
echo $current
currentOS=$current
echo $currentOS
if [ $currentOS >= cutOffOS ] ; then
    echo "10.8 or later"
    chflags nohidden ~/Library
else
    echo "oh well"
fi

运行上述脚本时的输出:

10.8.4

10.8

10.8

/Users/Tuan/Desktop/IDFMac.app/Contents/Resources/script:line 11:[:10.8:一元运算符预期

哦,好吧

1 个答案:

答案 0 :(得分:1)

忽略sw_vers可以返回带有3个部分(例如10.7.5)的版本“数字”的(非常真实的)问题,bash无法处理浮点数,只能处理整数。您需要将版本号分解为整数组件,并单独测试它们。

cutoff_major=10
cutoff_minor=7
cutoff_bug=0

osString=$(sw_vers -productVersion)
os_major=${osString%.*}
tmp=${osString#*.}
os_minor=${tmp%.*}
os_bug=${tmp#*.}

# Make sure each is set to something other than an empty string
: ${os_major:=0}
: ${os_minor:=0}
: ${os_bug:=0}

if [ "$cutoff_major" -ge "$os_major" ] &&
   [ "$cutoff_minor" -ge "$os_minor" ] &&
   [ "$cutoff_bug" -ge "$os_bug" ]; then
    echo "$cutoff_major.$cutoff_minor.$cutoff_bug or later"
    chflags nohidden ~/Library
else
    echo "oh well"
fi