如果未手动分配值,则浮点值不起作用

时间:2013-11-25 20:53:26

标签: shell if-statement floating-point

我需要检查百分比变化是否> 0,== 0,< 0,和NULL。 所以我得到了get_count(),它返回SELECT语句的结果......:

get_count () {
    sqlplus -s un/pass <<!
    set heading off
    set feedback off
    set pages 0
    select trunc(PRNCT_CHANGE, 3) 
    FROM SEMANTIC.COUNT_STATISTICS;
   exit;
!
}

count=$(get_count $1) #possible values: -0.789, -10.999, 11.897, 20, 1, 0...

if [ -z "$count" ]; then
    echo "The count percentage change returns null value"
elif [[ "$count" -gt 0 ]]; then
    echo "The count percentage change ($count) is greater than zero"
elif [[ "$count" == 0 ]]; then
    echo "The count percentage change stays unchanged (is zero)"
elif [[ "$count" =~ ^[\-0-9] ]]; then
    echo "The count percentage change is $count" 
else
   echo "$count  ... Something else is wrong here"
fi

如果我手动为$count分配值,即:

count=-0.987

这很有效。

否则如果我让get_count()方法返回值,它总是跳转到else语句...

我应该以某种方式转换传递给$count变量的值吗?

1 个答案:

答案 0 :(得分:1)

bash无法理解浮点值。您需要使用bc等外部程序进行比较:

if [ -z "$count" ]; then
    echo "The count percentage change returns null value"
elif [[ $(echo "$count > 0" | bc ) -eq 1 ]]; then
    echo "The count percentage change ($count) is greater than zero"
elif [[ $(echo "$count < 0" | bc ) -eq 1 ]]; then
    echo "The count percentage change ($count) is less than zero"
elif [[ "$count" == 0 ]]; then
    echo "The count percentage change stays unchanged (is zero)"
else
   echo "$count  ... Something else is wrong here"
fi