Introduction
Lock files help make sure only one copy of a script runs at a time. This stops problems from running duplicates.
Lock files help make sure only one copy of a script runs at a time. This stops problems from running duplicates.
#!/bin/bash LOCKFILE=/tmp/myscript.lock if [ -e "$LOCKFILE" ]; then echo "Script is already running. Exiting." exit 1 fi touch "$LOCKFILE" # Your script commands here rm -f "$LOCKFILE"
The lock file is a simple file that marks the script is running.
Check if the lock file exists before starting work.
#!/bin/bash LOCKFILE=/tmp/myscript.lock if [ -e "$LOCKFILE" ]; then echo "Already running." exit 1 fi touch "$LOCKFILE" # Do work rm -f "$LOCKFILE"
flock for safer locking with file descriptor.#!/bin/bash LOCKFILE=/tmp/myscript.lock exec 200>"$LOCKFILE" || exit 1 flock -n 200 || { echo "Script running, exiting."; exit 1; } # Do work here # Lock released automatically on script exit
This script creates a lock file to prevent multiple runs. It simulates work with sleep, then removes the lock.
#!/bin/bash LOCKFILE=/tmp/example.lock if [ -e "$LOCKFILE" ]; then echo "Script is already running. Exiting." exit 1 fi touch "$LOCKFILE" echo "Script started. Doing work..." sleep 2 echo "Work done." rm -f "$LOCKFILE"
Always remove the lock file at the end to allow future runs.
If the script crashes, the lock file might stay. You can add checks for stale locks.
Lock files stop multiple script instances from running at once.
Check for the lock file before starting work.
Remove the lock file when done to allow new runs.
if [ -e /tmp/myscript.lock ]; then echo "Script already running" exit 1 else touch /tmp/myscript.lock echo "Running script" rm /tmp/myscript.lock fiWhat will be the output if the lock file exists?
if [ -e /tmp/myscript.lock ]; then echo "Already running" exit 1 fi touch /tmp/myscript.lock # script work here rm /tmp/myscript.lockBut sometimes multiple instances run simultaneously. What is the likely problem?
Pass the test and this pattern moves unknown