尝试将复杂的 bash 字符串放入 mqtt 消息中

尝试将复杂的 bash 字符串放入 mqtt 消息中

我试图适应以下字符串的输出(这是一个简单的数字)

df -hl | grep '/dev/mapper/4tb' | awk '{;percent+=$5;} END{print percent}' | column -t

进入以下 mqtt 消息

mosquitto_pub -h 192.168.1.1 -p 1883 -u user -P password -t disk_usage/4tb -m *[here sould go the output of the previous command]*

我已经尝试了以下脚本及其许多变体(不同的引号和括号等),但我仍然无法弄清楚。

#!/bin/sh
var1='{df -hl | grep '/dev/mapper/4tb' | awk '{;percent+=$5;} END{print percent}' | column -t}'
echo $var1

mosquitto_pub -h 192.168.1.65 -p 1883 -u mqtt -P mqtt_password -t GC01SRVR/disk_usage -m "{\"Content\": $var1}"

答案1

echo "static string 1 $(cmd # this is replaced by the stdout output of cmd) string 2"

echo "abc $(date --rfc-3339=seconds) xyz"
abc 2021-11-19 20:12:18+01:00 xyz

所以在你的情况下

echo "mosquitto_pub -h 192.168.1.1 -p 1883 -u user -P password -t disk_usage/4tb -m $(df -hl | grep '/dev/mapper/4tb' | awk '{;percent+=$5;} END{print percent}')"

或者

cmd_output="$(df -hl | grep '/dev/mapper/4tb' | awk '{;percent+=$5;} END{print percent}')"

static_string="mosquitto_pub -h 192.168.1.1 -p 1883 -u user -P password -t disk_usage/4tb -m "

echo "${static_string}${cmd_output}"

相关内容