在bash脚本中使用小数点时,会出现非法数字。

我对bash脚本很陌生,我在脚本中遇到了一个问题。

#!/bin/sh
timestamp() {
        date +"%Y-%m-%d %T"
}
LOGDIR="/home/pi/tempcontroller_rum1.log"

VALUE=28

TEMP=$(cat /home/pi/temperaturloggar/rum1.txt)
STATUS=`cat /sys/class/gpio/gpio18/value`
echo `timestamp` "  Info:    Temperature: $TEMP"        >>$LOGDIR
if [ $TEMP -le $VALUE ] && [ $STATUS -eq 0 ]
        then
        echo `timestamp` "Too Cold, Heater started."    >>$LOGDIR
        echo "1">/sys/class/gpio/gpio18/value
        print $TEMP
elif [ $TEMP -ge $VALUE ]  && [ $STATUS -eq 1 ]
        then
        echo `timestamp` "Warm enough, Heater stoped."  >>$LOGDIR
        echo "0">/sys/class/gpio/gpio18/value
        print $TEMP
fi

文件“rum1”包含一个带有多个小数的数字,我认为这可能是问题所在,因为当我运行脚本时,我得到了

./tempcontroller_rum1.sh: 12: [: Illegal number: 25.10000038147

./tempcontroller_rum1.sh: 17: [: Illegal number: 25.10000038147

有什么建议吗?我需要脚本从.txt文件中读取,将其与VALUE进行比较,然后根据VALUE是低于还是高于GPIO打开/关闭。

如果我手动将rum1.txt设置为24。脚本可以运行,但我会遇到以下警告/错误。

Warning: unknown mime-type for "24" -- using "application/octet-stream" Error: no such file "24"

我该如何解决这个问题?

我的Lua脚本写入rum.txt,我可以将其四舍五入:

commandArray = {}
if (devicechanged['Rum1']) then
    local file = io.open("/home/pi/temperaturloggar/rum1.txt", "w")
    file:write(tonumber(otherdevices_temperature['Rum1']))
    file:close()
end
return commandArray
点赞
用户1283554
用户1283554

你可以使用bc进行浮点数比较:

$ VALUE=28
$ TEMP=25.10000038147
$ bc<<<"$TEMP < $VALUE"
1

在你的情况下:

if [ $(bc<<<"$TEMP < $VALUE") -eq 1 ] && [ $STATUS -eq 0 ]
2015-02-04 10:09:31
用户107090
用户107090

为了回答评论中的问题,请使用 math.floor 向下舍入,例如:

file:write(math.floor(otherdevices_temperature['Rum1']))

要向上舍入,使用以下代码:

file:write(math.floor(otherdevices_temperature['Rum1']+0.5))
2015-02-04 10:31:42
用户4527906
用户4527906

现在我的脚本已经像它应该的那样工作了,如果有其他人有和我一样的问题,我想发布代码。

#!/bin/bash
timestamp() {
    date +"%Y-%m-%d %T"
}
LOGDIR="/home/pi/tempcontroller_rum1.log"
VALUE=23
TEMP=$(cat /home/pi/temperaturloggar/rum1.txt)
STATUS=`cat /sys/class/gpio/gpio18/value`
echo `timestamp` "  Info:    Temperature: $TEMP"        >>$LOGDIR
if [ $(bc<<<"$TEMP < $VALUE") -eq 1 ] && [ $STATUS -eq 0 ]
    then
    echo `timestamp` "Too Cold, Heater started."    >>$LOGDIR
    echo "1">/sys/class/gpio/gpio18/value
elif [ $(bc<<<"$TEMP < $VALUE") -eq 0 ] && [ $STATUS -eq 1 ]
    then
    echo `timestamp` "Warm enough, Heater stoped."  >>$LOGDIR
    echo "0">/sys/class/gpio/gpio18/value
fi
2015-02-04 12:37:42