How to clear ALL retained mqtt messages from Mosquitto?

JohnL picture JohnL · Apr 19, 2016 · Viewed 37k times · Source

I've seen the mosquitto_pub -h [server] -r -n -t [XYZ] syntax for clearing out one off messages. My problem is the device developers have posted a lot of garbage messages.

I have a Java/Paho code base that I'd like to modify to do this automatically as needed, but I can't seem to publish a zero byte message. I tried

client.publish(topic,null);

...but that didn't seem to work.

Any suggestions on how to delete everything, en mass?

Answer

Gussoh picture Gussoh · Jan 29, 2017

Here is how to do it properly with a shell script.

#!/bin/sh
echo "cleaning " $1 " :: usage: cleanmqtt <host>"
mosquitto_sub -h $1 -t "#" -v --retained-only | while read line; do mosquitto_pub -h $1 -t "${line% *}" -r -n; done

Just put it in a file called somthing like

finally_a_working_way_to_remove_all_those_annoying_messages.sh

Then run

sh finally_a_working_way_to_remove_all_those_annoying_messages.sh localhost

This solution is quite crude. You cant specify what to delete or anything. You may have to abort with ctrl-c after you can assume that it has received all the messages.