These mosquitto_pub mosquitto_sub examples are the commands you will actually reach for when testing devices, debugging topics and scripting MQTT. Each one is copy-paste ready and runs against the free public broker broker.connectmq.com, so you can verify the behavior yourself in seconds. By the end you will know how to exercise QoS, retained messages, Last Will, TLS and MQTT 5 properties from the command line.
Before You Start
Install the Mosquitto clients:
# Debian / Ubuntu / Raspberry Pi OS
sudo apt install mosquitto-clients
# macOS
brew install mosquitto
# Windows: install Mosquitto from mosquitto.org; the installer includes mosquitto_pub.exe and mosquitto_sub.exe
Check with mosquitto_pub --help; the first line shows the version. Several examples below need version 2.x (for -x, %j output and some MQTT 5 options). The full option reference lives in the official mosquitto_pub manual.
Three rules for the public broker:
- Always pass a unique, non-empty client ID with
-i. Two clients with the same ID disconnect each other. - Use a unique topic prefix. The examples use
connectmq/demo/x7q2/; replacex7q2with your own random string. - The public area is readable by everyone. Never publish credentials or personal data.
To keep commands short, set two shell variables (bash/zsh):
H="-h broker.connectmq.com -p 1883"
T="connectmq/demo/x7q2"
Open two terminals: one for mosquitto_sub, one for mosquitto_pub.
Basic mosquitto_pub mosquitto_sub Examples
1. Subscribe to one topic
mosquitto_sub $H -i sub-x7q2 -t "$T/hello"
2. Publish a message
mosquitto_pub $H -i pub-x7q2 -t "$T/hello" -m "hello from the CLI"
3. Subscribe to everything under your prefix and print topics (-v prints the topic before the payload)
mosquitto_sub $H -i sub-x7q2 -t "$T/#" -v
4. Single-level wildcard: all temperature topics, any room
mosquitto_sub $H -i sub-x7q2 -t "$T/+/temperature" -v
5. Several topic filters in one client
mosquitto_sub $H -i sub-x7q2 -t "$T/+/temperature" -t "$T/+/humidity" -v
6. Publish JSON (single quotes stop the shell from interpreting the braces and quotes)
mosquitto_pub $H -i pub-x7q2 -t "$T/kitchen/temperature" -m '{"value": 21.8, "unit": "C"}'
On Windows cmd.exe, escape inner quotes instead: -m "{\"value\": 21.8}".
QoS and Sessions
7. Publish and subscribe with QoS 1
mosquitto_sub $H -i sub-x7q2 -t "$T/alarms" -q 1 -v
mosquitto_pub $H -i pub-x7q2 -t "$T/alarms" -q 1 -m "door open"
The effective QoS is the lower of the publish QoS and the subscription QoS. For the full picture see MQTT QoS levels explained.
8. Watch the protocol exchange with -d (debug shows CONNECT, PUBLISH, PUBACK and friends)
mosquitto_pub $H -i pub-x7q2 -t "$T/alarms" -q 2 -m "test" -d
You will see PUBLISH, PUBREC, PUBREL and PUBCOMP for QoS 2. This is the fastest way to prove what a broker actually does.
9. Persistent session: receive messages published while you were offline
# Subscribe once with a fixed ID, clean session disabled, then Ctrl+C
mosquitto_sub $H -i sub-persist-x7q2 -c -q 1 -t "$T/queue" -v
# While it is stopped, publish at QoS 1
mosquitto_pub $H -i pub-x7q2 -q 1 -t "$T/queue" -m "queued while offline"
# Reconnect with the same ID and -c: the message is delivered
mosquitto_sub $H -i sub-persist-x7q2 -c -q 1 -t "$T/queue" -v
10. MQTT 5 session expiry (keep the session for 300 seconds after disconnect)
mosquitto_sub $H -V 5 -i sub-persist-x7q2 -c -x 300 -q 1 -t "$T/queue" -v
The public broker keeps sessions for at most 30 minutes.
Retained Messages
11. Publish a retained state
mosquitto_pub $H -i pub-x7q2 -t "$T/pump1/state" -r -m "running"
Any new subscriber gets running immediately, without waiting for the next publish.
12. Show only retained messages, then exit
mosquitto_sub $H -i sub-x7q2 -t "$T/#" -v --retained-only -W 3
-W 3 exits after 3 seconds, handy for scripts that snapshot current state.
13. Ignore old retained messages (-R skips messages with the retain flag set on arrival)
mosquitto_sub $H -i sub-x7q2 -t "$T/#" -v -R
14. Delete a retained message (publish an empty retained payload)
mosquitto_pub $H -i pub-x7q2 -t "$T/pump1/state" -r -n
15. Clear every retained message under your prefix
mosquitto_sub $H -i cleaner-x7q2 -t "$T/#" --remove-retained --retained-only -W 3
Use this with care on any broker; it removes retained state for everything the filter matches.
Last Will and Testament
16. Register a Last Will that marks the client offline
mosquitto_sub $H -i device-x7q2 -t "$T/device1/cmd" \
--will-topic "$T/device1/status" --will-payload "offline" --will-retain --will-qos 1
In another terminal, watch status with mosquitto_sub $H -i watch-x7q2 -t "$T/device1/status" -v, then kill the first process abruptly (close the terminal or kill -9). After the keep-alive times out, the broker publishes offline. A clean Ctrl+C sends DISCONNECT and does not trigger the Will. Set a short keep-alive with -k 10 to see it faster.
Scripting and Output Control
17. Receive exactly N messages, then exit
mosquitto_sub $H -i sub-x7q2 -t "$T/kitchen/temperature" -C 1
Great in shell scripts: TEMP=$(mosquitto_sub ... -C 1).
18. Custom output format with timestamps
mosquitto_sub $H -i sub-x7q2 -t "$T/#" -F "@Y-@m-@dT@H:@M:@S %t %p"
19. JSON output for piping into jq
mosquitto_sub $H -i sub-x7q2 -t "$T/#" -F "%j" | jq -c '{topic, payload}'
20. Publish each line of a file or stdin as a separate message
printf '20.1\n20.4\n20.9\n' | mosquitto_pub $H -i pub-x7q2 -t "$T/kitchen/temperature" -l
Use -f firmware.bin to send a whole file as one message, or -s to send all of stdin as one message. The public broker caps messages at 64 KB.
21. A tiny sensor simulator (respect the public limit of 10 messages per second per client)
while true; do
mosquitto_pub $H -i sim-x7q2 -t "$T/lab/temperature" \
-m "{\"value\": $((RANDOM % 10 + 20)), \"ts\": $(date +%s)}"
sleep 1
done
TLS and Authentication
22. Encrypted connection on port 8883
# Linux: use the system CA bundle
mosquitto_sub -h broker.connectmq.com -p 8883 --capath /etc/ssl/certs \
-i tls-x7q2 -t "$T/#" -v
On macOS or Windows, point --cafile at a PEM file containing the ISRG Root X1 certificate (Let's Encrypt), since those systems do not expose a PEM directory. If you see Error: A TLS error occurred, check the CA file path and your system clock.
23. Private broker with credentials
mosquitto_pub -h YOUR_BROKER_HOST -p 8883 --capath /etc/ssl/certs \
-i YOUR_CLIENT_ID -u YOUR_USERNAME -P YOUR_PASSWORD \
-t "factory1/line1/cnc1/telemetry" -q 1 -m '{"spindle_rpm": 8000}'
Avoid putting passwords in shell history in shared environments. Mosquitto 2.x reads options from a config file: put -u and -P lines in ~/.config/mosquitto_pub (and mosquitto_sub) with restrictive permissions.
MQTT 5 Properties
24. Content type, user property and message expiry
mosquitto_pub $H -V 5 -i pub-x7q2 -t "$T/kitchen/temperature" -m '{"value": 22}' \
-D PUBLISH content-type application/json \
-D PUBLISH user-property source cli-test \
-D PUBLISH message-expiry-interval 60
View the properties on the subscriber side with -V 5 -F "%t %p | %P" (%P prints user properties). The MQTT 5 features guide explains when each property is useful.
25. Request/response with mosquitto_rr
# Responder: read the response topic (%R) of each request and answer it
while true; do
RT=$(mosquitto_sub $H -V 5 -i resp-x7q2 -t "$T/rpc/time" -C 1 -F "%R")
mosquitto_pub $H -V 5 -i resp-pub-x7q2 -t "$RT" -m "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
done &
# Requester: sets the response topic, waits for one reply and prints it
mosquitto_rr $H -V 5 -i req-x7q2 -t "$T/rpc/time" -e "$T/rpc/time/reply" -m "now?" -W 5
mosquitto_rr sets the MQTT 5 response topic on the request, subscribes to it and prints the first reply. The shell responder is good enough for a demo; a real service in Python or Node would also echo the correlation data so concurrent requests can be matched.
Quick Option Reference
| Option | Tool | Meaning |
|---|---|---|
-h, -p |
both | Host and port (1883 TCP, 8883 TLS) |
-i |
both | Client ID (always set it) |
-t, -m |
both / pub | Topic, message |
-q |
both | QoS 0, 1 or 2 |
-r, -n |
pub | Retain flag, null (empty) payload |
-c, -x |
sub | Disable clean session, session expiry (MQTT 5) |
-v, -F |
sub | Print topic, custom format |
-C, -W |
sub | Exit after N messages, timeout in seconds |
-R, --retained-only, --remove-retained |
sub | Retained message handling |
-V 5, -D |
both | MQTT 5 and properties |
-d |
both | Protocol debug output |
-k |
both | Keep-alive in seconds |
Troubleshooting
Connection Refused: identifier rejected: empty or invalid client ID. Pass-iwith a unique value.- Connection drops right after connect: another process uses the same client ID.
Error: Connection refusedon port 8883: you forgot--capathor--cafile, so the client tried plain TCP on a TLS port.- Nothing arrives: compare the subscribe filter and publish topic character by character; MQTT topics are case-sensitive and a leading
/creates an extra empty level. - Messages stop after a burst: public broker limits (10 messages per second per client, 10 subscriptions per client, 8 topic levels).
Moving from Tests to Production
The public MQTT test broker is perfect for learning these commands, but devices in the field need private credentials and isolation. A hosted MQTT broker from ConnectMQ gives you TLS on 8883, WebSocket on 8083 and 8084, MQTT 3.1.1 and 5.0, and credentials generated per broker; every command above works by swapping in example 23's flags. For other command-line options, read the comparison of MQTT CLI tools, and if you prefer a GUI, see desktop MQTT explorer apps. The MQTT client libraries guide shows how to move these tests into code.
Get Started with ConnectMQ
Create a private broker at app.connectmq.com on the free Serverless plan, no credit card required. Copy the generated username, password and client ID into examples 22 and 23, and use the portal's live topic explorer alongside mosquitto_sub to confirm every message.
Frequently Asked Questions
Why does mosquitto_sub show nothing when I publish?
Most often the topic filter does not match: check case, slashes and wildcards. Also make sure the two clients use different client IDs, and add -d to see whether the subscription was granted.
How do I send a message without a payload with mosquitto_pub?
Use -n. Combined with -r, it deletes the retained message on that topic.
Can mosquitto_pub use MQTT 5?
Yes, from Mosquitto 1.6 onward. Add -V 5 (or -V mqttv5) and set properties with -D <command> <property> <value>.
Do I need the Mosquitto broker installed to use these commands?
No. The mosquitto-clients package contains only the command-line clients, and they work with any MQTT broker, including ConnectMQ.



