The Pragmatic Addict

Monitor Mosquitto (MQTT) with a bash script

Background

Home automation is a relatively new thing for me. After various starts and stops I’ve settled on the Zigbee standard using zigbee2mqtt and mosquitto. Against the norm I’ve opted to stay away from Home Assistant and rely on MQTT Dash for my UI.

This has worked very well but I didn’t have a decent solution for handling events of devices. Most important are my flood sensors I’ve now installed. What I’ve come up with is a systemd service that starts a batch file for monitoring.

The script

The script relies on two packages mosquitto-client for connectivity and jq for easy JSON parsing.

In my case I am monitoring ‘water_leak’ on the device.

The script’s second line uses an associative array (hash table) to keep track of state. Because the sensor has a ridiculous bounce it reports multiple times with the same info. This will track the state change and run indefinitely until canceled.

Most important is the last line defining which topic you with to monitor. You can actually use the -t option multiple times for multiple sensors.

/etc/mosquitto/mosquitto-monitor.sh

#!/bin/bash
declare -A last=()
 
while read topic 
do 
        topicname=`echo $topic | cut -d ' ' -f1`
        payload=`echo $topic | cut -d ' ' -f2`
        state=`echo $payload | jq -r '.water_leak'`
 
        echo "$topicname $payload $state last: ${last[$topicname]}"

# Insert Actions Here
 
        last[$topicname]=$state
 
done < <(mosquitto_sub -t 'zigbee2mqtt/floodsensor' -F '%t %p')

Running as a service

/usr/lib/systemd/system/mosquitto-monitor.service

[Unit]
Description=Monitors mosquitto for events /etc/mosquitto/mosquitto-monitor.sh
After=mosquitto.service
ConditionFileIsExecutable=/etc/mosquitto/mosquitto-monitor.sh
 
[Service]
ExecStart=/etc/mosquitto/mosquitto-monitor.sh
 
[Install]
WantedBy=default.target
This is where the script becomes a background service. All you have to do is create the service file and issue the following commands to register, enable and start the service:

systemctl daemon-reload
systemctl enable mosquitto-monitor.service
systemctl start mosquitto-monitor.service

Created: 2026-05-07 Modified: 2026-05-07