-   Linux - Newbie (
-   -   Bash script to check if process is running and send email (

depam 04-08-2009 12:28 AM

Bash script to check if process is running and send email

Can you please help on giving me a script that will check certain process (httpd, xmail) every hour and send email if it is not running?

I already have a tool to send an email automatically but I need a bash script to include in crontab to run every hour.


laitcg 04-08-2009 01:04 AM

if ! `pidof program` ;then
mail -s "program bit the dust" root@localhost

replacing program with your programs cli name

anotherlinuxuser 04-08-2009 01:11 AM

Here's a simple shell you can use:

Scripts starts on next line:

ps -ef | grep -v grep | grep "some command in the process list" \
> dev/null
if [ $? -ne 0 ]; then
'put your email command here.'

# End of Script

The 'ps -ef' will list all processes on the system.
The '| grep -v grep' will filter out our 'ps' process to prevent a false

The '| grep "some command in the process list"' will find, or will not find, the process you are checking.
When selecting a string to look for, keep in mind you have to look for something unique to the program you want find. A generic search for "mail" will match 'sendmail', 'qmail', etc. so try to include some white space, like: ' xmail '. Don't include dates or process numbers, as they will change.

The '\' just means continue the same command on the next line.
We redirect any output to '> /dev/null' so we don't get a email from cron every time the script runs.

The 'if [ $? -ne 0 ]; then' checks if the second grep found what we were looking for. Since we are only concerned when the process is not found, we check for a not equal to 0 return from the grep command.

Replace the 'put your email command here.' with your own email command.
Remember that cron only sets a basic environment, so if your email program is not in one the standard program dirs,
"/usr/local/bin:/usr/bin:/bin", you must use a complete path to the program, ie.: /usr/mydir/bin/myemailprog {options}
You can put more than 1 command inside the if ... fi statement.
Good luck.

All times are GMT -5. The time now is 09:34 AM.