1

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?

4
  • 1
    @αғsнιη: Kinf of, but in a very roundabout way, with loops and ifs. The answer we have here is a one-liner! :-)
    – Ardwena
    Nov 6 '20 at 6: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? Nov 6 '20 at 8: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.
    – Ardwena
    Nov 6 '20 at 9:15
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
  • 2
    Thank you! That does it. :-)
    – Ardwena
    Nov 6 '20 at 5: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.
    – user414777
    Nov 6 '20 at 6:41
-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.