$linuxjunkies
>

mosquitto_pub(1)

Publish a message to an MQTT broker using the Mosquitto client.

UbuntuDebianFedoraArch

Synopsis

mosquitto_pub [options] -t topic [-m message]

Description

mosquitto_pub is a simple MQTT client that publishes a single message to a broker and exits. It connects to an MQTT server, sends a message to a specified topic, and disconnects. This is useful for scripting, automation, and one-off message publishing tasks.

Messages can be provided via the -m flag, read from standard input, or loaded from a file. QoS (Quality of Service) levels and message retention are supported.

Common options

FlagWhat it does
-t, --topic <topic>MQTT topic to publish to (required)
-m, --message <message>The message payload to publish; if not specified, reads from stdin
-h, --host <hostname>MQTT broker hostname or IP address (default: localhost)
-p, --port <port>MQTT broker port (default: 1883)
-u, --username <username>Username for broker authentication
-P, --pw <password>Password for broker authentication
-q, --qos <qos>QoS level: 0 (at most once), 1 (at least once), or 2 (exactly once)
-r, --retainMark message as retained so new subscribers receive it
-f, --file <file>Read message payload from file instead of -m
-d, --debugEnable debug messages
-i, --id <client-id>Set client ID for the connection
--cafile <file>PEM file containing trusted CA certificates for TLS

Examples

Publish a temperature reading to a remote broker on a custom host

mosquitto_pub -h broker.example.com -t 'home/temperature' -m '22.5'

Publish a message from standard input (piped) to localhost

echo 'Hello MQTT' | mosquitto_pub -t 'test/topic'

Publish a retained message so future subscribers see it immediately

mosquitto_pub -t 'sensors/status' -m 'online' -r

Publish to an authenticated MQTT broker with username and password

mosquitto_pub -h mqtt.server -u admin -P mypass -t 'secure/data' -m 'payload123'

Publish with QoS level 2 (exactly once delivery guarantee)

mosquitto_pub -t 'alerts/warning' -m 'High CPU usage detected' -q 2

Publish the contents of a file as the message payload

mosquitto_pub -t 'logs/app' -f /var/log/application.log

Publish multiple messages in a loop with 1-second intervals

for i in {1..5}; do mosquitto_pub -t 'test' -m "Message $i"; sleep 1; done

Related commands