Kill a process fast with bash

I’m continuing my bash journey! I’m calling it that even though a lot would work in other shells as well, e.g., sh and zsh. So to be honest, it could be called; my shell journey.

Sometimes you wanna kill a process and not run ps aux, then copy-paste the PID and finally kill it over and over…

ps aux | grep puma-dev | awk '{print $2}' | tail -n 1 | xargs kill

Why so many commands?

  1. ps aux shows all the running processes
  2. grep puma-dev picks the lines with the text “puma-dev” in it
  3. awk '{print $2}' pick the values in the second column (that’s where the PID is when using ps aux)
  4. tail -n 1 picks one line from the bottom, i.e., the last line
  5. xargs kill takes the previous extracted value (the last PID) and kills it, something like: kill 666

If you wanna kill all the processes found, remove the tail -n 1 command.

Optimizations

To skip the awkward (pun intended awk) commands of parsing the PID, we can use pgrep.

pgrep puma-dev | xargs kill

We can even boil the command down to one with pkill:

pkill puma-dev

Which one is the best?

I usually use a combination of those commands as pkill doesn’t give you much feedback of what happened. Sometimes I wanna see everything with ps aux. And sometimes I just don’t care or more often I want to repeatably kill the same program over and over 🐍.

References