0

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?

  • 1
    @αғsнιη: Kinf of, but in a very roundabout way, with loops and ifs. The answer we have here is a one-liner! :-) –  Nov 06 '20 at 06:18
  • @Ardwena I doubt if the answer here could find all running instances. I don't know, maybe it does but never used pidof, 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
  • 1
    @αғsнιη: So far it works correctly. Here's what I am doing: My script spins off a bunch of background processes, mostly monitoring, logging, reporting and stuff -- nothing too important. Every now and then, a new idea comes to mind, and I revise the script a bit, and then just run it. I don't want to specifically go hunting for the old instances, I just want the new revision to take effect. (Lazy, I know :) So, this thing does the job. Tested. –  Nov 06 '20 at 09:15

2 Answers2

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
    Thank you! That does it. :-) –  Nov 06 '20 at 05:39
  • 2
    This 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