I'm trying to write a bash script that will execute and if a certain condition (grep) is met then the script exits but if the grep is not found within X seconds then I'd like it to echo something and then exit. The biggest issue is one of the commands in it is long running and I have to exit it otherwise is just keeps going and going until I close the terminal.
To help, we're using the Pusher CLI https://pusher.com/docs/pusher_cli/documentation to ping IoT devices out in the field.
To get this to work I'm first subscribing to the channel and then backgrounding this process, waiting 5 seconds and then sending the ping. I'm then greping the output from the background process and looking for a "pong" in the response and exiting if it's found. This is all working great, the problem I'm running into is when a "pong" is not found (device offline) and the subscribe process just keeps running indefinitely in the background and I have no sense that the device is offline.
So I'd like something that can fire off the commands and then after 10 seconds kill everything but if the "pong" is found then kill everything that way.
Here is the script that I have going so far
ping () {
subscribe_channel $1 &
sleep 5
ping_channel $1
}
ping_channel () {
pusher channels apps trigger --app-id $appid --channel $1 --event $event --message $message
}
subscribe_channel () {
while read -r line; do
echo $line
if [[ $(echo $line | grep "pong") ]]; then
echo "online"
exit
fi
done < <(pusher channels apps subscribe --app-id $appid --channel $1)
}
ping channel
[[ $line = *pong* ]]is literally orders of magnitude faster than running a pipeline invoking grep inside a process substitution.