If you're going to do this, you need to deal with the possibility that the script will die unceremoniously, leaving the lock file behind. This adds a trap, makes the lock file identify the machine, PID, and date/time the lock was asserted, and examines that information and attempts to determine whether the lock is really valid rather than blindly assuming that it is.
#!/bin/bash
Lock=/some-where/rsync-is-runningLog=/some-where/rsync.logif [ -f $Lock ]
then
read <$Lock Machine PID RDate
if [ `uname -n` = "$Machine" ]
then
if [ "x`ps -ocmd= -p $PID`" = "x$0" ]
then
echo "`date` - An instance of rsync is already running on this server: `ps -fp $PID`" >>$Log
exit
else
echo "`date` Ignoring invalid lock entry: `cat $Lock`"
fi #[ "x`ps -ocmd= -p $PID`" = "x$0" ]
else
echo "`date` - An instance of rsync appears to be already running on $Machine: `cat $Lock`" >>$Log
exit
fi #[ `uname -n` = "$Machine" ]
fi #[ -f $Lock ]
# If we make it this far, actually do it.
echo "`date` - Starting synchronization" >> $Logtrap 'rm $Lock; exit' 1 2 3 4 5 6 7 8 10 11 12 13 14 15
echo `uname -n` $$ `date` >$Lock
# ... your script here ...
echo "`date` - Finished synchronization" >> $Log
rm $Lock
You could probably even use rcmd to validate the alleged PID of the process on the other machine, if you wanted to go to the trouble. Or just have one server be the designated initiator of the rsync, which simplifies things greatly.