如何将mosquitto_sub输出重定向至.txt文件并每次更新时覆盖文件
Hey there! I get exactly what you're trying to do—you want your newtest.txt to only ever hold the latest MQTT message, not keep appending every new one. Let's break down why your current command isn't working, then fix it with a couple simple approaches.
Why your current command appends instead of overwriting
When you use > newtest.txt with mosquitto_sub, the shell truncates the file once when it starts the mosquitto_sub process. After that, mosquitto_sub keeps running and writes each new message to the same open file descriptor—so every new line gets added to the end, rather than replacing the whole file.
Solution 1: Loop to fetch one message at a time (great for low-frequency messages)
If your MQTT messages don't come super often, you can run mosquitto_sub in a loop. It will fetch just one message, overwrite the file, exit, then restart to wait for the next message:
while true; do mosquitto_sub -h 192.168.1.10 -t "application/7/device/a8404117b18312e9/rx" -C 1 > newtest.txt done
The -C 1 flag tells mosquitto_sub to stop after receiving 1 message. Each loop iteration uses > newtest.txt to truncate the file and write the latest message fresh.
Solution 2: Keep the connection open (better for frequent messages)
For a more efficient approach that avoids repeated MQTT reconnects, use a pipe and a while read loop to overwrite the file every time a new message arrives:
mosquitto_sub -h 192.168.1.10 -t "application/7/device/a8404117b18312e9/rx" | while read -r message; do echo "$message" > newtest.txt done
Here's how this works:
mosquitto_substays connected and sends each new message to the pipe- The
while readloop captures each message line-by-line echo "$message" > newtest.txtoverwrites the file with the latest message every time (since>truncates the file before writing)
If your messages might include special characters like backslashes or embedded newlines, swap echo for printf to handle them more reliably:
mosquitto_sub -h 192.168.1.10 -t "application/7/device/a8404117b18312e9/rx" | while read -r message; do printf "%s\n" "$message" > newtest.txt done
Either of these methods will give you the behavior you want—only the most recent MQTT message will live in your text file!
内容的提问来源于stack exchange,提问作者Bob Grattan

