How to clear ALL retained mqtt messages from Mosquitto?

There are 2 options for this using the paho client code depending on which of the 2 publish methods you use.

MqttMessage msg = new MqttMessage(new byte[0]);
msg.setRetained(true);
client.publish(topic, msg);

or

client.publish(topic, new byte[0],0,true);

The other option would be to stop mosquitto and delete the persistence file and restart


Mosquitto client provides --remove-retained option:

mosquitto_sub -h $host --remove-retained -t '#' -E

Tunning -t can handle specific topics to be cleared.


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.