3

I'm running a cron job every minute, which launches a bash shell script:

# Automatically reboot the server if it goes down
* * * * * /root/auto-restart.sh

I can manually run the script, but whenever I try running it through a cron job it won't run. I've debugged a bit and found this command to be the culprit:

pgrep -fcl auto-restart.sh

To summarize, when run manually, that command returns the correct value and only lists auto-restart.sh if the script's currently running (as it should).

But when the cron job launches it, it shows the output of pgrep -fl auto-restart.sh as follows (when it's running):

3110 sh
3111 auto-restart.sh

Here's the bit of code I'm working with:

scriptcheck=`pgrep -fcl auto-restart.sh`
if [ $scriptcheck -gt 1 ]; then
    echo "auto-restart.sh script already in use. Terminating.."
    #cron job debugging..
    echo "[DEBUG] scriptcheck returning greater than 1" > /tmp/debug.output
    echo "[DEBUG] Value of scriptcheck: ${scriptcheck}" >> /tmp/debug.output
    echo "[DEBUG] contents:" >> /tmp/debug.output
    pgrep -fl auto-restart.sh >> /tmp/debug.output
    exit
fi

Complete script here: https://pastebin.com/bDyzxFXq

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
johndoe
  • 31
  • 3

1 Answers1

5

When cron runs /root/auto-restart.sh, it runs it using sh, along the lines of sh -c /root/auto-restart.sh. Since you’ve used the -f option with pgrep, pgrep looks for auto-restart.sh anywhere in the running processes’ command lines; so it matches auto-restart.sh as well as sh -c /root/auto-restart.sh. The latter appears as plain sh in the output of pgrep -l.

pgrep -c auto-restart.sh

will give you the behaviour you’re after. (I dropped -l because it’s meaningless with -c.)

(Your server probably has a watchdog timer, which might be more appropriate — although I imagine that if the server is still running sufficiently well to run cron jobs, but is otherwise considered down, then the watchdog wouldn’t trip.)

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164