I can use mosquitto_sub
to subscribe to broker for a specific topic, say test_topic,
mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic
I can also pipe grep for a specific keyword, say valve_closed,
mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic | grep "valve_closed"
This would only output a newline with "valve_closed", every time that particular topic broadcasts "valve closed" message.
Input,
Line 1: mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic | grep "valve_open"
Line 2: mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic | grep "valve_closed"
Output,
Line 1: valve_closed
Now, my question is, how can I pipe a command such that if grep "valve_closed"
is true, then execute another command.
I've tried chaining a command like echo "Okay so now Valve is Closed"
with another |
pipe command,
mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic | grep "valve_closed" | echo "Okay, so now Valve is Closed"
But this simply runs the echo command with output "Okay, so now Valve is Closed"
, even when I group grep+echo within parentheses.
I also tried using AND operator &&
,
mosquitto_sub -h MOSQUITTO_BROKER_HOSTNAME -t test_topic | grep "valve_closed" && echo "Okay, so now Valve is Closed"
While this waits for grep to match string valve_closed
as soon as it finds a match, it would execute echo "Okay, so now Valve is Closed"
.
I've also tried using if statement, however any inclusion of conditional statement seems to break the polling nature of message_sub
which constantly monitors a given topic and prints out its output.
I'm kind of lost as to how I can use mosquitto_sub to retrieve messages and execute shell commands/scripts based on message content. Thanks for reading.