Shell – Error handling in shell script

shellshell-scripttrap:

I wrote a shell script run_script.sh, which includes a step which creates an empty file run_script.lck. Everytime the shell script was called by the cronjob, it will check for the existence of run_script.lck. If the lock is presence, it indicates that run_script.sh is already running and hasn't finished yet. The run_script.lck file will be deleted in the end of the program.

The trouble is to remove the lock file when the shell script crashed and before it exits.

I wrote a line like this:

trap "rm -f run_script.lck" EXIT

But it will remove the lock file in an undesired condition like this:

I execute run_script.sh in shell A, and it is running, the lock file was created. Then I execute it again in shell B, and it said that the script is already running and the script will be aborted. However, because the trap received an EXIT signal including the signal from shell B, which is exiting an aborted script, then it removes the lock file. And the script in shell A is still running, but the lock was deleted and anyone can call another run_script.sh again while there is already one script running.

Any idea how to solve this?

Best Answer

To illustrate Ignacio's answer (use following protocol: first check if lockfile exists and then install the trap), you can solve the problem like this:

$ cat test2.sh
if [ -f run_script.lck ]; then
  echo Script $0 already running
  exit 1
fi
trap "rm -f run_script.lck" EXIT
# rest of the script ...
Related Question