Linux: Make your scripts safe, don't run a script if an instance of the script is already run

Assume the following scenario, you have created a script that does log analysis and writes results in files, but the script in case of…

Linux: Make your scripts safe, don't run a script if an instance of the script is already run
Photo by Nick Fewings on Unsplash

Assume the following scenario, you have created a script that does log analysis and writes results in files, but the script in case of executing while another instance of the script is already running will cause wrong results, how we can prevent this? using pidof ! let's see how!

Modify the script

Open the script with your favorite editor and append the following after #!/bin/bash

pidof -o %PPID -x "$(basename "$0")" > /dev/null && { echo "Script is already running"; exit 1; }

Let's see how it works

pidof -o %PPID -x "$(basename "$0")" > /dev/null:

  • pidof finds the process ID of a running program.
  • -o %PPID excludes the parent process ID to avoid detecting the current shell as an instance of the script.
  • -x includes the script file name in the search to find all instances.
  • "$(basename "$0")" extracts the script name from its full path.
  • > /dev/null: Discards the output of pidof.

&& { echo "Script is already running"; exit 1; }:

  • If pidof finds another instance, it prints a message and exits.

Conclusion

This is a very small but handy oneliner that can help you make your scripts safer! i hope you enjoyed this article!