0
0
Bash Scriptingscripting~5 mins

Lock files for single instance in Bash Scripting

Choose your learning style9 modes available
Introduction

Lock files help make sure only one copy of a script runs at a time. This stops problems from running duplicates.

When you want to prevent a backup script from running twice at once.
To avoid multiple instances of a data processing script running simultaneously.
When a script updates shared resources and must not overlap.
To ensure a scheduled job does not start if the last run is still active.
Syntax
Bash Scripting
#!/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.

Examples
Basic lock file check and removal after work.
Bash Scripting
#!/bin/bash
LOCKFILE=/tmp/myscript.lock

if [ -e "$LOCKFILE" ]; then
  echo "Already running."
  exit 1
fi

touch "$LOCKFILE"

# Do work

rm -f "$LOCKFILE"
Using flock for safer locking with file descriptor.
Bash Scripting
#!/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
Sample Program

This script creates a lock file to prevent multiple runs. It simulates work with sleep, then removes the lock.

Bash Scripting
#!/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"
OutputSuccess
Important Notes

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.

Summary

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.