How can I kill from bash all python processes excluding one python script. (I know its name, but its pid can be changed sometimes).

I need kind of pkill -f "python" but with excluding the python specific script.

Please advise.


ps aux |grep python |grep -v 'pattern_of_process_you_dont_want_to_kill' |awk '{print $2}' |xargs kill

Update: step-by-step explanation as requested in comments

  • ps aux |grep python - show all processes which are matching python pattern
  • grep -v 'pattern_of_process_you_dont_want_to_kill' - exclude process you don't want to kill
  • awk '{print $2}' - show second field of output, it is PID.
  • xargs kill - apply kill command to each input arg (PID).

If you are not familiar with xargs command, i'd advise you to do not worry if you do not understand it right away. It could appear quite tricky for the first time. I posted very simple example of its usage, you may google for more.

  • 1
    Great, but can you please explain how does it work, For example what is awk '{print$2}' and xargs kill? – user370717 Aug 16 '16 at 10:26
  • awk '{print $2}' - prints second field of ps output, in current case it is PID. xargs applies kill command to each PID – user1700494 Aug 16 '16 at 10:31
  • 1
    Putting that in a comment is nice, but I'd rather vote for your answer after that well-formatted comment was integrated into your answer. – chicks Aug 16 '16 at 12:10

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.