Search This Blog

Tuesday, July 23, 2024

Bash scrip check if another instance of my shell script is running

#!/bin/bash

# Check if another instance of my shell script is running
if [[ `pgrep -f $0` != "$$" ]]; then
	echo "Another instance of shell already exist! Exiting"
	echo "[$(date)] : $0 : Process is already running with PID $pid"
	exit 1
fi

# Rest of the script goes here
echo "[$(date)] : $0 : is now running..."
Explanation: 
  1. $0 gives filename of your running script.
  2. $$ gives PID of your running script.
  3. pgrep searches for process by name and returns PID.
  4. pgrep -f $0 searches by filename, $0 being the current bash script filename and returns its PID.

No comments:

Post a Comment