Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Ensure Only One Instance of a Bash Script Is Running on Linux
When running a bash script on Linux, it's important to ensure that only one instance of the script is running at a time. This is especially important for scripts that perform critical tasks, such as database updates or email sending. Running multiple instances of the same script simultaneously can cause conflicts, data loss, and other errors. In this article, we will discuss different methods to ensure that only one instance of a bash script runs on Linux.
Using Flock
One way to ensure that only one instance of a bash script runs on Linux is to use the flock command. The flock command creates a file lock and is built into most Linux distributions. It's a simple and efficient way to ensure that only one instance of a script runs at a time.
We can trust this approach because there will be no race conditions. Also, all locks on a file are released when the process completes. These benefits make flock a safe way to ensure that only one instance is running. The flock program is an implementation of the flock system call.
By default, flock blocks until the lock is released and then continues without errors. We can use the -n parameter to use flock in a non-blocking way. This will cause flock to exit immediately with an error when there is another lock on the file.
Running an External Script
We can use flock to wrap script execution like this
flock -n /var/lock/dobackup.lock ./dobackup.sh
Now let's assume that our script is currently running. Let's see what happens if we execute the previous line again
flock --verbose -n /var/lock/dobackup.lock ./dobackup.sh
flock: failed to get lock
echo $?
1
We can see that flock informed us that it could not acquire the lock and exited with the value 1 (error). This means that another instance has the lock. When flock fails, it does not run the script parameter, which prevents more than one instance of "dobackup.sh" from running.
Using Flock within the Script
We can use flock inside the script like this
#!/bin/bash
another_instance()
{
echo "There is another instance running, exiting"
exit 1
}
(
flock -n 100 || another_instance
DEST=/home/backup/`date +%s`
mkdir -p "$DEST"
rsync -avz root@host:/home/web "$DEST/."
) 100>/var/lock/dobackup.lock
In this case, we call flock with a file descriptor and enclose everything we need to protect in parentheses (a subshell) and redirect it to the file we use as lock. We call flock at the beginning with the file descriptor used in the redirect. So if flock exits with an error, we know there is another instance running.
Once the subshell is finished, the lock file is closed and the lock is automatically released.
Using the PID File
Another way to ensure that only one instance of a bash script runs on Linux is to use a PID file. A PID file is a special file that contains the process ID (PID) of the running script. By checking the PID file, we can determine if the script is already running and if so, exit the script with an error message.
To implement this method, we can add the following code to the beginning of our script
#!/bin/bash
PIDFILE="/var/run/myscript.pid"
if [ -f $PIDFILE ]; then
pid=$(cat $PIDFILE)
if kill -0 $pid 2>/dev/null; then
echo "Script is already running with PID $pid"
exit 1
else
echo "Stale PID file found, removing..."
rm -f $PIDFILE
fi
fi
echo $$ > $PIDFILE
# Your script logic here
echo "Script is running..."
sleep 30
# Clean up PID file on exit
trap 'rm -f $PIDFILE' EXIT
This code checks for the presence of the PID file in the specified path. If the PID file exists, the script reads the PID from the file and checks if the process is still running by sending a null signal (kill -0) to the process. If the process is still running, the script exits with an error message. If the process is not running, the script removes the stale PID file and creates a new one with the current process ID.
The trap command ensures that the PID file is cleaned up when the script exits normally or is terminated.
Comparison of Methods
| Method | Advantages | Disadvantages |
|---|---|---|
| Flock | Race-condition free, automatic cleanup, system call based | Requires lock file location, not available on all systems |
| PID File | Simple to implement, widely supported | Race conditions possible, manual cleanup required |
Best Practices
Use flock when available as it provides the most robust solution
Always use absolute paths for lock files and PID files
Ensure proper cleanup of lock files using trap handlers
Test your locking mechanism thoroughly in your environment
Conclusion
Ensuring that only one instance of a bash script runs on Linux is crucial for preventing conflicts and data corruption. The flock method is generally preferred due to its race-condition free nature and automatic cleanup, while PID files offer a simpler alternative for basic use cases. Choose the method that best fits your specific requirements and environment.
