How to avoid shell scripts being run multiple times at the same time

  
 

For example, there is a periodic (cron) backup mysql script, or rsync script, if there is an accident, the running time is too long, it is likely that the next backup cycle has begun, the current cycle of the script has not run Obviously we are not willing to see such a situation happen.

In fact, as long as you make some changes to the script itself, you can avoid it being repeatedly run.

#!/bin/bashLOCK_NAME="/tmp/my.lock"if [[ -e $LOCK_NAME ]] ; thenecho "re-entry, exiting"exit 1fi### Placing lock filetouch $ LOCK_NAMEecho -n "Started..."### Start normal process### Normal process end### Removing lockrm -f $LOCK_NAMEecho "Done."

When the script starts running, Create the /tmp/my.lock file. If you run this script again and find that my.lock exists, it will exit and delete the file when the script finishes running.

In most cases, there is nothing wrong with doing this. Accident 1) If you run this script twice at the same time, both processes will find that my.lock does not exist and can continue to execute. Accident 2) If the script quits unexpectedly during the run, there is no time to delete the my.lock file, then it is tragedy.

Modify as follows:

#!/bin/bashLOCK_NAME="/tmp/my.lock"if ( set -o noclobber; echo "$$" > "$ LOCK_NAME") 2> /dev/null; thentrap 'rm -f "$LOCK_NAME"; exit $?' INT TERM EXIT### Start normal process### Normal process end### Removing lockrm -f $LOCK_NAMEtrap - INT TERM EXITelseecho "Failed to acquire lockfile: $LOCK_NAME." echo "Held by $(cat $LOCK_NAME)"exit 1fiecho "Done."

set -o noclobber Meaning:< Br>

If set, bash does not overwrite an existing file with the >, >&, and <> redirection operators.

This will ensure that my.lock can only be one The process is created. More reliable than touch.

trap can capture various signals and then process them: INT is used to handle ctrl+c to cancel script execution. TERM is used to handle kill -TERM pid. EXIT is not clear

In addition, it is not valid for kill -9. .

Remember that N years ago, in the php group, the grass people also asked this question, the answer we gave was ps aux

Copyright © Windows knowledge All Rights Reserved