It’s very easy to implement locking in a bash script using
mkdir. While there are other methods like:
- Touch a file and check its availability
- Use special tools like
lockfile-progsin Debian or
lockfilein other distributions
- Find the running process with
mkdir for simple bash scripts which only should run once at any given time.
A folder can only be created once with the same name, if
mkdir is told to create this folder again, it ends with an error.
This error can be used to check if a script is already running. Of course there should be some cleanup if a script terminates before it cleanly ends or the
script will never run again until you manually delete the folder. This can be done with traps, which executes cleanup functions on signals.
Here is an skeleton bash script which provides simple locking:
Some things needs explanations:
- At the end of every bash script, the Trap handler 0 is called. Using the variable
UNLOCKI can check if
exit_on_endis called the second time. Otherwise everytime the script ends the lock is removed, regardless if it should or not.
exit_on_endis called with the current exit code when it’s called to preserve it
- If the cleanup did not succeed, the check if the PID really exists can handle this case
Start your script below
### My script: and have some fun.