How to Receive Retained Messages Using mosquitto_sub vs mqtt-cli

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_sub

  • mqtt-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-only filters 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 jq for JSON processing.

  • More scriptable and filterable than mosquitto_sub.

  • Supports TLS, structured output, and richer MQTT options.


πŸ†š Feature Comparison Table

Feature

mosquitto_sub

mqtt-cli + jq

Feature

mosquitto_sub

mqtt-cli + jq

Retained message filter

βœ… --retained-only

βœ… via jq

JSON Output

❌ Plain text only

βœ… --json-output

Topic Wildcards

βœ…

βœ…

TLS/Authentication Support

βœ…

βœ…

Filtering (retain=true only)

🚫

βœ… via jq

Script/Automation Friendly

⚠️ Basic only

βœ… Excellent

Dependency

Low (1 CLI tool)

Medium (CLI + jq)


🧠 Summary

Use Case

Recommended Tool

Use Case

Recommended Tool

Quick testing, simple CLI use

mosquitto_sub

Structured filtering, automation

mqtt-cli + jq


Β Related articles