I'm writing a bash script that kills a bunch of processes selected by certain criteria and then quits. The only problem is that those criteria apply to the script and its parent processes (bash, sshd) itself, so in order to avoid killing the script before it has done its work, I first get the matching processes with ps, then filter out the script and its parents with sed and finally kill the remaining processes with kill.

Now I'm wondering whether I could simplify this to a single pkill call, but obviously that can only work if pkill is guaranteed to kill itself and its parent processes last if they occur in the list of processes to kill.

Is there such a guarantee implemented into pkill?

2 Answers 2


pkill never kills itself, just like pgrep nerver lists itself; pkill does exit after killing each process matching the criteria, except itself. pkill does kill its parent(s) if it(they) match the criteria, but if the parent is a shell unless you use an unignorable signal (usually only -9 aka -[SIG]KILL) the shell normally ignores it. If it includes your sshd that will indeed kill your session, and with it your shell and (most?) other processes, which is usually undesired.

You might want to use pgrep to find the processses, perhaps with -l or -lf, and do additional checks before killing them.

  • There is a note in the man page confirming this too: "The running pgrep or pkill process will never report itself as a match."
    – Leponzo
    Commented Dec 10, 2022 at 3:14

It seems that with pkill from procps-ng, pkill -f CAN match its own command line and kill itself, while BSD pkill on macOS doesn't seem to do this. (I tested "pkill from procps-ng 3.3.17")

See linux - Prevent process from killing itself using pkill - Stack Overflow for options to avoid this.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .