I have this user crontab (accessed via the command crontab -e):
# m h dom mon dow command
*/3 * * * * sh /home/FRAPS/Desktop/cronCheck.sh
The script cronCheck.sh looks like that:
#!/bin/sh
SERVICE='Script'
if ps ax | grep -v grep | grep -i "$SERVICE" > /dev/null
then
echo "######## $SERVICE service running, everything is fine ##################\n" >> CronReport.txt
else
echo "$SERVICE is not running. Launching it now\n" >> CronReport.txt
perl Script.pl
fi
When I launch the script (cronCheck.sh) from its own directory, it works like a charm, but when cron launches it, it always “# $SERVICE service running, everything is fine ###”
despite ‘Script’ is not running.
Thanks,
Here’s an even better way to write that conditional:
By using
ps -e -o commyou avoid having to do the sillygrep -v grepthing, because only the actual process name appears in the ps output, not the arguments. Andgrep -cFicounts up the matches and gives you a number, so you don’t have to deal with the exit status of a pipeline.Also, as other posters have implied, you should lead off this script by setting the
PATHvariable.You might or might not want to put
/usr/local/binat the beginning of that list, depending on your system. Don’t do it if you don’t need anything from there.Final piece of advice: When writing scripts that will execute without user supervision (such as cron jobs), it’s a good idea to put
set -eat the beginning. That makes them exit unsuccessfully if any command fails.