I needed a bash script that would only email me once if a process stopped on my linux box, so I put together a very simple, but effective script that:

  • Continuously runs in a loop
  • Keeps the script running if a flag file is not found
  • Stops the script if the flag file is found
  • Sends an email when the script reaches the end of the continuous loop
#!/bin/bash

FLAG_FILE="/home/tmp/flagfile"
service="[.]/bin/bash ./myscript.sh"

while [ ! -f "${FLAG_FILE}" ]
do
if ps -ef | grep "[l]ivestream.sh"; then
        echo "Service is running"
else
        touch "$FLAG_FILE"
        echo "Sending notification"
        echo "Mayday! Mayday! My process stopped!" | mail -s "Service has stopped!" [email protected]
fi
sleep 5
done
rm FLAG_FILE

I’ll explain each line in detail below.

We define the path for our flag file at the beginning of the script:

FLAG_FILE="/home/flagfile"

Next line defines the service that we want to monitor:

service="[.]/bin/bash ./myscript.sh"

This line starts the continuous loop and will stop if the flag file exists in the specified path we defined in FLAG_FILE. Notice that we put “sleep 5” at the end of the loop. This is in place to throttle the script so that it only runs once every 5 seconds:

while [ ! -f "${FLAG_FILE}" ]

We’ll check if our service name is found in running processes:

if ps -ef | grep "[m]yscript.sh"; then

If the process is found, we start the loop over and do the check again. If the process is not found, we create the FLAG_FILE and send an email.

touch "$FLAG_FILE"
echo "Sending notification" 
echo "Mayday! Mayday! My process stopped!" | mail -s "Service has stopped!" [email protected]

 

That’s it, your script is now ready for use. It will essentially check if a certain process is running every 5 seconds and if it cannot find the process, it creates a FLAG_FILE and sends only one email alert.
The script resets itself when it exits the main loop by deleting the FLAG_FILE.

To run the script in the background, run it like so with nohup. This will keep the script running even if you close your terminal window:

nohup myscript.sh &