首页 > 解决方案 > 在 mosquitto 中接收到某个消息时,Shell 脚本无法离开 while 循环

问题描述

因此,如果某个消息到达我的 Raspberry pi 上,我试图让该脚本运行以退出 while 循环。可悲的是它不起作用。如果消息到达,它不会以某种方式识别 j 设置为 false。

  #!/bin/bash


# This script subscribes to a MQTT topic using mosquitto_sub.
# On each message received, you can execute whatever you want.


set -x
j=true


while [[ $j == true ]]  # Keep an loop to reconnect when connection lost/broker$

do
mosquitto_sub -t parsec.stop -C 1 | while read -r payload

do
        # Here is the callback to execute whenever you receive a message:
        if [[ "$payload" == "parsec.stop" ]] || [[ $j == false ]]; then
         echo "Rx MQTT: ${payload}"
        j=false
       fi
  done

 sleep 1  # Wait until reconnection
done # &  # Discomment the & to run in background (but you should rather run$

echo "end"

这是我执行脚本时在我的 Shell 中得到的

+ j=true
+ [[ true == true ]]
+ mosquitto_sub -t parsec.stop -C 1
+ read -r payload
+ [[ parsec.stop == \p\a\r\s\e\c\.\s\t\o\p ]]
+ echo 'Rx MQTT: parsec.stop'
Rx MQTT: parsec.stop
+ j=false
+ read -r payload
+ sleep 1
+ [[ true == true ]]
+ mosquitto_sub -t parsec.stop -C 1
+ read -r payload

如您所见,它确实在消息到达后立即声明j = false 。但它不会离开循环。仍然显示[[ true == true]]

标签: bashwhile-looppipemosquittosubshell

解决方案


推荐阅读