How to Receive Retained Messages Using mosquitto_sub vs mqtt-cli
Hereβs a comparison-style How-To guide that explains how to receive retained messages using both mosquitto_sub and mqtt-cli, with clear instructions and use cases for each.
This guide outlines how to retrieve retained MQTT messages using two popular tools:
mosquitto_submqtt-cli
Both tools allow subscribing to topics and filtering for retained messages, but they differ in flexibility and output formatting.
Β Instructions
π Prerequisites (Common to Both)
A running MQTT broker (e.g., HiveMQ)
Network access to the broker (IP or hostname and port)
Valid username/password if authentication is enabled
Known topic structure or use of wildcard (
#)
πΉ Option 1: Using mosquitto_sub
β Best for:
Quick testing
Simple environments
Minimal dependencies
π§ Command
mosquitto_sub -h <broker-host> -p <port> -u <username> -P <password> -t '#' -v --retained-onlyπ Output
Plain text in the format:
<topic> <message>π Notes
--retained-onlyfilters out non-retained messages.Doesn't format JSON or allow structured filtering.
Not interactive or script-friendly for complex use cases.
πΉ Option 2: Using mqtt-cli + jq
β Best for:
Advanced filtering (e.g., JSON retained flag)
Automation or logging
Production diagnostics
π§ Command
mqtt subscribe \
--host <broker-host> \
--port <port> \
--identifier retained-subscriber \
--topic '#' \
--qos 0 \
--user <username> \
--password <password> \
--json-output \
| jq -c 'select(.retain == true)'π Output
JSON formatted messages, e.g.:
{"topic":"sensor/temp","payload":"22.5","retain":true}π Notes
Requires
jqfor JSON processing.More scriptable and filterable than
mosquitto_sub.Supports TLS, structured output, and richer MQTT options.
π Feature Comparison Table
Feature |
|
|
|---|---|---|
Retained message filter | β
| β
via |
JSON Output | β Plain text only | β
|
Topic Wildcards | β | β |
TLS/Authentication Support | β | β |
Filtering (retain=true only) | π« | β
via |
Script/Automation Friendly | β οΈ Basic only | β Excellent |
Dependency | Low (1 CLI tool) | Medium (CLI + jq) |
π§ Summary
Use Case | Recommended Tool |
|---|---|
Quick testing, simple CLI use |
|
Structured filtering, automation |
|