如何从文本文件提取温度值作为比较器,条件执行Python脚本
温度判断脚本实现方案
提取温度值到变量
先通过sed提取温度值并保存为变量,避免重复执行命令:
temp=$(sed -n 's/^temp=\(.*\)/\1/p' realtimegauges.txt)
浮点比较与执行对应脚本
Bash原生不支持浮点数值比较,这里提供两种可行方案:
方案1:使用bc工具
if (( $(echo "$temp < 30" | bc -l) )); then python3 myfile1.py else python3 myfile2.py fi
bc -l用于处理浮点运算,echo "$temp < 30" | bc -l会返回1(条件成立)或0(条件不成立),再通过(( ))进行整数判断。
方案2:使用awk工具
echo "$temp" | awk '{ if ($1 < 30) { system("python3 myfile1.py") } else { system("python3 myfile2.py") } }'
直接借助awk的浮点比较能力,通过system命令调用对应Python脚本。
完整可执行脚本
将以上步骤整合为一个完整脚本:
#!/bin/bash # 从文件提取温度值 temp=$(sed -n 's/^temp=\(.*\)/\1/p' realtimegauges.txt) # 根据温度判断执行脚本 if (( $(echo "$temp < 30" | bc -l) )); then python3 myfile1.py else python3 myfile2.py fi
内容的提问来源于stack exchange,提问作者BobW
相关产品推荐
相关产品推荐

