mqttメッセージに複雑なbash文字列を入れようとしています。

mqttメッセージに複雑なbash文字列を入れようとしています。

次の文字列(簡単な数字)の出力を調整しようとしています。

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

おすすめ記事