Bash

試圖將復雜的 bash 字元串放入 mqtt 消息中

  • November 19, 2021

我正在嘗試擬合以下字元串的輸出(這是一個簡單的數字)

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}"
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}"

引用自:https://unix.stackexchange.com/questions/678292