Bash – How to kill all python processes except one from bash

bash

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.

Best Answer

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.