I am trying to write a bash script that detects if a service has changed state. I have this so far:
while true; do
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
echo notinuse
else
echo inuse
fi
sleep 5
done
It works but it will endlessly write when the service is up or down, and I only want it to report on the first instance of a state change. So report when the service was down, and then up as well as when it was up and then went down.
I started to create loop counters and comparing to a previous run but I got into a complete mess of variables. Can anyone help?
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
echo notinuse
notify_status="notinuse-sent"
else
echo inuse
notify_status="inuse-sent"
fi
while true; do
if [ -z "$(netstat -tulpn | grep 51827)" ];
then
if [ $notify_status = "notinuse-sent" ]; then
echo "already notified"
else
echo notinuse
$notify_status="notinuse-sent"
fi
else
if [ $notify_status = "inuse-sent" ]; then
echo "already notified"
else
echo inuse
$notify_status="inuse-sent"
fi
fi
sleep 5
done