Backup script / Test if script is already running

Hello everyone,

I have 2 questions :

1) I have a backup shell script, let's call it backup.sh, that is called every hour as a cron job.
As a matter of fact a backup could last more than one hour.
It mounts a NAS and then do some rsync on important directories, so really I don't want to start the srcipt again if the previous backup is not finished.
In order to test if the script is not already running, I am doing this :

if [ `ps-ef | grep -c backup.sh` -eq 1 ] # backup.sh is not already running
then
# execute backup.sh
fi

Is it the best way to do this test?
Do you have any suggestion for improvement?

2) Could you please share or point out where I could find some well thought backup script?

Many thanks for your help and keep up the good work!

A traditional way to tell if a service is already running is a PID file. Save the process ID in a temporary file and delete it on exit. If the PID file exists, and the PID is still valid, then another backup is running. Even if the process dies unexpectedly and doesn't delete, it should be able to cope since the odds of something else snapping up the same PID are small.

This is how services often work and much more reliable than trying to grub through ps's own text output for answers.

#!/bin/sh

if [ -f /tmp/myservice-pid ]
then
        read PID < /tmp/myservice-pid

        # Check if the PID in the file still exists
        # If it does, backup is running, and we should skip this round.
        if ps "$PID" >/dev/null 2>/dev/null
        then
                echo "Already running" >&2
                exit 1
        fi
fi

# Either create new file, or replace it with our own
echo $$ > /tmp/myservice-pid
# Delete it on exit just to be extra sure
trap "rm -f /tmp/myservice-pid" EXIT

# Continue below

...

Many thanks for your reply that is brilliant and very useful!
Thanks again,