1

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

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.

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.