0

I have the following in my crontab to sync my folders on the servers as they are run on round robin DNS settings it syncs every minute.

* * * * * rsync -ar --delete -e ssh user@skynet.rizzler.se:/home/user/folder1/ /home/user/folder1/ >/dev/null 2>&1
* * * * * rsync -ar --delete -e ssh user@skynet.rizzler.se:/home/user/folder2/ /home/user/folder2/ >/dev/null 2>&1

This Rsync works for small files, but it's getting bigger so I am wondering how I can get this into a script, put that script into my crontab and each time the script is run, it will check if it's running. If the script is running, it will do nothing; if it's not running, it should go ahead and start the rsync.

Anyone know how I can do this?

donjuedo
  • 2,475
  • 18
  • 28
Rizzzler
  • 193
  • 2
  • 12
  • 2
    One easy-but-not-error-proof way would be to just `touch` a run flag file and `rm` it when the job is done, then check for the existence of the flag and bail if it exists. One problem with that approach depending on the complexity of your job is if it dies mid-execution it'll never remove the flag. – swornabsent Jun 04 '15 at 16:54

2 Answers2

2

You could write the script's PID into a file with echo $$ > /var/run/rsync_job.pid

Then when you start you could first check if that file exists, and if it does read the PID from it and see if that process still exists like

if ps -p $PID &>/dev/null; then
    # it's still running
    exit
fi
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

As swornabsent noted in the comments, you can use file-based locks, though that SO link identifies some good reasons not to use it. See this SO question about quick-and-dirty locking in shell scripts, which has a great answer about advantages to directory-based locks instead.

To identify whether a process is running, you may also choose to use pgrep, though that may not be a good idea in the general case due to the time after the check and before the process starts up.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251