Guides

mosquitto_pub and mosquitto_sub: Command Examples & Cheat Sheet

Copy-paste mosquitto_pub and mosquitto_sub examples: flags table, QoS, retained messages, auth, TLS, MQTT 5, files, line mode and filtering output with -F.

Updated · 7 min read

mosquitto_pub and mosquitto_sub are the Swiss-army knives of MQTT. They ship with Mosquitto (on Debian/Ubuntu in the mosquitto-clients package — see installing Mosquitto) and work against any MQTT broker, not just Mosquitto. This cheat sheet collects the flags and examples you actually need.

The basic round trip

Subscribe in one terminal, publish in another:

Terminal 1
mosquitto_sub -h test.mosquitto.org -t 'testmqtt/cheatsheet/#' -v
Terminal 2
mosquitto_pub -h test.mosquitto.org -t 'testmqtt/cheatsheet/hello' -m 'hello world'

Always quote topics in the shell: # starts a comment in bash and zsh, and + or * can be expanded unexpectedly. Wildcard rules are explained in MQTT topics and wildcards.

Watch the messages in the online client

Flags cheat sheet

FlagToolMeaning
-hbothBroker host (default localhost)
-pbothPort (default 1883, or 8883 with TLS)
-tbothTopic; mosquitto_sub accepts it several times
-mpubMessage payload
-qbothQoS 0, 1 or 2
-rpubSet the retain flag
-u / -PbothUsername / password
-ibothClient ID (random if omitted)
-vsubPrint topic before payload
-dbothDebug: print every MQTT packet sent and received
--cafilebothCA certificate for TLS (also --capath, --cert, --key)
-V mqttv5bothProtocol version: mqttv31, mqttv311 (default) or mqttv5
-lpubRead stdin and send each line as a separate message
-fpubSend the contents of a file as one message
-spubSend all of stdin as one message
-npubSend an empty (zero-length) message
-WsubExit after N seconds
-CsubExit after receiving N messages
-RsubDo not print stale retained messages
-FsubCustom output format (topic, payload, QoS, timestamps…)

mosquitto_pub examples

QoS 1 with credentials and a fixed client ID
mosquitto_pub -h broker.example.com -u alice -P 'secret' -i sensor-01 \
  -q 1 -t 'home/livingroom/temp' -m '21.5'
JSON payload (single quotes keep the shell away from it)
mosquitto_pub -t 'devices/42/state' -m '{"on":true,"brightness":80}'
Send a file, or stream lines from another command
mosquitto_pub -t 'firmware/blob' -f ./payload.bin
tail -f /var/log/app.log | mosquitto_pub -t 'logs/app' -l

Set and clear retained messages

bash
# store "online" as the retained value
mosquitto_pub -t 'devices/42/status' -m 'online' -r

# clear it: empty payload + retain flag
mosquitto_pub -t 'devices/42/status' -r -n

Every new subscriber gets the retained value immediately until you clear it. Background: MQTT retained messages.

mosquitto_sub examples

Several topics, verbose output, QoS 1
mosquitto_sub -h broker.example.com -u alice -P 'secret' -q 1 -v \
  -t 'home/+/temp' -t 'home/+/humidity'
Grab one message and exit (great in scripts)
value=$(mosquitto_sub -t 'home/livingroom/temp' -C 1 -W 10)
echo "temperature: $value"
Ignore stale retained messages
mosquitto_sub -t 'devices/#' -v -R
Custom format with -F
# ISO-8601 timestamp, QoS, topic, payload
mosquitto_sub -t 'devices/#' -F '%I q%q %t %p'

# just the payloads, one per line, e.g. for jq
mosquitto_sub -t 'devices/+/state' -F '%p' | jq .

Common -F tokens: %t topic, %p payload, %q QoS, %r retain flag, %l payload length, %I ISO-8601 time, %U Unix time with nanoseconds, %x payload as hex.

TLS examples

Server verified by a specific CA
mosquitto_sub -h broker.example.com -p 8883 --cafile ca.crt -t 'secure/#' -v
Broker with a public (e.g. Let's Encrypt) certificate
mosquitto_pub -h broker.example.com -p 8883 --capath /etc/ssl/certs \
  -u alice -P 'secret' -t 'secure/hello' -m 'over TLS'
Client certificate (mutual TLS)
mosquitto_pub -h broker.example.com -p 8883 --cafile ca.crt \
  --cert client.crt --key client.key -t 'secure/hello' -m 'mTLS'

--insecure skips hostname verification — handy for a lab, dangerous anywhere else. Which port is which is summarised in MQTT ports.

MQTT 5 examples

bash
# publish with a message expiry and content type
mosquitto_pub -V mqttv5 -t 'jobs/1' -m '{"run":true}' \
  -D publish message-expiry-interval 60 \
  -D publish content-type application/json

# subscriber prints properties with -F
mosquitto_sub -V mqttv5 -t 'jobs/#' -F '%t %p (expiry %E)'

-D sets an MQTT 5 property for a given packet type. See MQTT 5 vs 3.1.1 for what the new properties do.

Scripting patterns

Because both tools exit with a non-zero status when they cannot connect, they slot neatly into shell scripts, cron jobs and health checks.

Simple broker health check
#!/usr/bin/env bash
# exits 0 if a message makes the round trip within 5 seconds
TOPIC="health/$(hostname)/$RANDOM"
mosquitto_sub -h broker.example.com -u monitor -P 'secret' -t "$TOPIC" -C 1 -W 5 > /dev/null &
SUB=$!
sleep 1
mosquitto_pub -h broker.example.com -u monitor -P 'secret' -t "$TOPIC" -m ping
wait $SUB && echo "broker OK" || { echo "broker FAILED"; exit 1; }
Publish a reading every 10 seconds
while true; do
  mosquitto_pub -t 'lab/cpu/load' -m "$(cut -d' ' -f1 /proc/loadavg)"
  sleep 10
done
Log everything to a file with timestamps
mosquitto_sub -h broker.example.com -u alice -P 'secret' -t 'devices/#' \
  -F '%I %t %p' >> mqtt.log

Opening a new connection for every message is fine for a few messages per second. For higher rates, keep one connection open with -l and pipe lines into it, or move to a client library.

Common mistakes

  • Unquoted # — mosquitto_sub -t devices/# works in some shells and silently becomes devices/ in others. Quote it.
  • Same client ID twice — running two commands with the same -i makes the broker disconnect the older one, which looks like a random drop. Leave -i out unless you need it, or use the client ID generator.
  • Expecting old messages — mosquitto_sub only receives messages published after it subscribes, plus the retained message per topic. Nothing else is stored for a new clean session.
  • Payload too large — brokers can cap message size; check yours with the packet size calculator.

What about WebSockets?

The standard mosquitto_pub and mosquitto_sub builds speak MQTT over TCP and TLS only; they cannot connect to a ws:// or wss:// endpoint. To test a broker's WebSocket listener use the online MQTT client or a library such as MQTT.js — and read MQTT over WebSockets for the details. If you want a ready-made snippet in your language instead, the MQTT code generator writes one for you.

Frequently asked questions

How do I delete a retained message with mosquitto_pub?

Publish an empty retained message to the same topic: mosquitto_pub -t the/topic -r -n. The broker removes the stored retained message for that topic.

How do I see the topic name in mosquitto_sub output?

Add -v (verbose). Each line is then printed as the topic followed by a space and the payload. For full control use -F with a format string such as -F "%t %p".

Can mosquitto_pub connect over WebSockets?

Not in the standard builds. mosquitto_pub and mosquitto_sub speak MQTT over TCP and TLS only. To test a WebSocket endpoint, use a browser-based client or a library such as MQTT.js.