views:

266

answers:

2

Greetings all. I'm setting up a cron job to execute a bash script, and I'm worried that the next one may start before the previous one ends. A little googling reveals that a popular way to address this is the flock command, used in the following manner:

flock -n lockfile myscript.sh
if [ $? -eq 1 ]; then
    echo "Previous script is still running!  Can't execute!"
fi

This works great. However, what do I do if I want to check the exit code of myscript.sh? Whatever exit code it returns will be overwritten by flock's, so I have no way of knowing if it executed successfully or not.

A: 
#!/bin/bash

if ! pgrep myscript.sh; then
  flock -n lockfile myscript.sh
fi

If I understand you right, you want to make sure 'myscript.sh' is not running before cron attempts to run your command again. Assuming that's right, we check to see if pgrep failed to find myscript.sh in the processes list and if so we run the flock command again.

SiegeX
+3  A: 

It looks like you can use the alternate form of flock, flock <fd>, where <fd> is a file descriptor. If you put this into a subshell, and redirect that file descriptor to your lock file, then flock will wait until it can write to that file (or error out if it can't open it immediately and you've passed -n). You can then do everything in your subshell, including testing the return value of scripts you run:

(
  if flock -n 200
  then
    myscript.sh
    echo $?
  fi
) 200>lockfile
Brian Campbell
ephemient
This works perfectly. Many thanks Brian.
Paul Accisano