I've seen suggestions how I can terminate my script if another instance of it is already running. My problem is the other way around: I would like to find a way to just kill all other instances of the same script -- if any -- and continue with executing my script. Is there any way to do that?
Asked
Active
Viewed 849 times
0
2 Answers
3
You can do something like... PIDS=$(pidof -x nameofyourscript)
to get all the pids, if any, including scripts. Then you can just kill $PIDS
EDIT: As the above would kill yout current script too, then revise the answer, adding option -o
like this: PIDS=$(pidof -x -o $$ nameofyourscript)
That -o $$
would make it omit the pid of your current script.
And better yet, instead of hardcoding nameofyourscript, just get its own name from $0
:
kill $(pidof -x -o $$ $0)
So put that near the beginning of your script, maybe with a 2>/dev/null
, in case it finds no other instances, and problem solved.
-
2
-
2This is both racy and unportable. On top of
pidof
being unreliable with finding the right process even the script is actually running. – Nov 06 '20 at 06:41
0
In your script:
# store the Process ID here
pidfile=/var/run/mypid.local
# If there's a stored PID, terminate with SIGKILL
[[ -f $pidfile ]] && kill -s 9 $(cat $pidfile)
# Save our PID for the next run to kill
echo "$$" >$pidfile
and, to clean up, just before you exit
,
rm $pidfile

waltinator
- 4,865
if
s. The answer we have here is a one-liner! :-) – Nov 06 '20 at 06:18pidof
, btw, retracted my vote for duplicate. however what if same script was run with different name? or same script name was running but with different codes? – αғsнιη Nov 06 '20 at 08:56