while循环中的变量只检查初始执行?

while循环中的变量只检查初始执行?

我编写了这个脚本,期望它在变量小于该值时运行给定的命令。但是当脚本最初执行时(根据日志)发生了什么,它检查变量“TEMP_NOW”并永远使用该初始值 - 就像它被缓存一样。我已经确认变量 TEMP_NOW 肯定正在改变。

感谢您的关注

#!/bin/bash
set -x
LOG_FILE=/home/mutt/pl/logs/pump.log
TEMP_NOW=$(cat /home/mutt/pl/logs/temp_now.txt)

while [ $TEMP_NOW -le 556 ]
do
        /home/mutt/pl/temp_pump_on.s
        echo ON > /home/mutt/pl/logs/pump_sch.txt
        echo $TEMP_NOW at `$(which date)` >> $LOG_FILE 2>&1 &
        sleep 5m
        /home/mutt/pl/temp_pump_off.s
        echo $TEMP_NOW at `$(which date)` >> $LOG_FILE 2>&1 &
        echo OFF > /home/mutt/pl/logs/pump_sch.txt
        sleep 20m
set +x 
done

日志:

mutt@mutt:~/pl/logs $ tail -10 pump.log
TEMP turned pump off at Sat Jan 13 13:07:01 CST 2018
125 at Sat Jan 13 13:07:01 CST 2018
TEMP turned pump ON at Sat Jan 13 13:27:01 CST 2018
125 at Sat Jan 13 13:27:01 CST 2018
TEMP turned pump off at Sat Jan 13 13:32:01 CST 2018
125 at Sat Jan 13 13:32:01 CST 2018 
TEMP turned pump ON at Sat Jan 13 13:52:01 CST 2018
125 at Sat Jan 13 13:52:01 CST 2018
125 at Sat Jan 13 13:57:01 CST 2018
TEMP turned pump off at Sat Jan 13 13:57:01 CST 2018
mutt@mutt:~/pl/logs $ ll temp_now.txt 
-rw-rw-rw- 1 pi pi 5 Jan 13 14:12 temp_now.txt
mutt@mutt:~/pl/logs $ cat temp_now.txt 
9625
mutt@mutt:~/pl/logs $ 

答案1

当然,该变量是静态的,它永远不会分配给循环内部,替换:

while [ $TEMP_NOW -le 556 ]

和:

while [ "$(cat /home/mutt/pl/logs/temp_now.txt)" -le 556 ]

以便在每个循环中重新读取该文件。

相关内容