Tuesday, November 13, 2018

How to Find and kill a process in Linux

For example, to show all the process IDs of mysql-workbench:

 $ ps -A | grep [m]ysql-workbench | awk '{print $1}'

The sample outpout:

12974
12982

The awk gives you the first field of each line, which is the PID.

The grep filters that based on your search string. [m]ysql-workbench is a trick that applies regex. It will then catch all other mysql-workbench processes but excluding grep itself.  If you use "grep mysql-workbench" directly, the process of grep itself will be caught too. Since [m]ysql-workbench != mysql-workbench, the process of grep will be excluded.

To kill them in one line:

$ kill $(ps -A | grep [m]ysql-workbench | awk '{print $1}')  (more reliable)

The $(x) is to execute x then put its output on the command line. So you end up with a command like "kill 12974 12982".

Or even simpler:

$ kill $(ps -A | awk '/[m]ysql-workbench/ {print $1}')