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 ?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With