Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if another instance of my shell script is running

GNU bash, version 1.14.7(1)

I have a script is called "abc.sh" I have to check this from abc.sh script only... inside it I have written following statement

status=`ps -efww | grep -w "abc.sh" | grep -v grep | grep -v $$ | awk '{ print $2 }'` if [ ! -z "$status" ]; then         echo "[`date`] : abc.sh : Process is already running"         exit 1; fi 

I know it's wrong because every time it exits as it found its own process in 'ps' how to solve it? how can I check that script is already running or not from that script only ?

like image 866
Jatin Bodarya Avatar asked May 29 '13 07:05

Jatin Bodarya


People also ask

How do you check if a shell script is already running?

From Shell Every running process has a PID. We use pidof command to determine the PID of our shell script. If the PID exists, it means the shell script is already running. In such cases, the above script will display a message saying that the process is already running.

How do you check if a script is running in the background?

Open Task Manager and go to Details tab. If a VBScript or JScript is running, the process wscript.exe or cscript.exe would appear in the list. Right-click on the column header and enable "Command Line". This should tell you which script file is being executed.


1 Answers

An easier way to check for a process already executing is the pidof command.

if pidof -x "abc.sh" >/dev/null; then     echo "Process already running" fi 

Alternatively, have your script create a PID file when it executes. It's then a simple exercise of checking for the presence of the PID file to determine if the process is already running.

#!/bin/bash # abc.sh  mypidfile=/var/run/abc.sh.pid  # Could add check for existence of mypidfile here if interlock is # needed in the shell script itself.  # Ensure PID file is removed on program exit. trap "rm -f -- '$mypidfile'" EXIT  # Create a file with current PID to indicate that process is running. echo $$ > "$mypidfile"  ... 

Update: The question has now changed to check from the script itself. In this case, we would expect to always see at least one abc.sh running. If there is more than one abc.sh, then we know that process is still running. I'd still suggest use of the pidof command which would return 2 PIDs if the process was already running. You could use grep to filter out the current PID, loop in the shell or even revert to just counting PIDs with wc to detect multiple processes.

Here's an example:

#!/bin/bash  for pid in $(pidof -x abc.sh); do     if [ $pid != $$ ]; then         echo "[$(date)] : abc.sh : Process is already running with PID $pid"         exit 1     fi done 
like image 58
Austin Phillips Avatar answered Sep 20 '22 14:09

Austin Phillips