How to Kill

7 Nov 2020


Let’s say I wrote a script to test a game to destruction and set it running multiple times on my laptop. And let’s say something went wrong, so the script stopped responding and I had to track down and kill multiple copies.

I can list all the processes:

% ps aux

root 116 0.0 0.0 4317488 656 ?? Ss 7Nov20 0:15.50 /System/Library/PrivateFrameworks/Uninstall.framework/Resources/uninstalld
root 114 0.0 0.0 6539408 5716 ?? Ss 7Nov20 3:06.28 /Applications/Backblaze.app/Contents/MacOS/bzserv
root 111 0.0 0.0 6306060 8920 ?? Ss 7Nov20 3:27.74 /usr/libexec/UserEventAgent (System)
root 110 0.0 0.0 4704948 1832 ?? Ss 7Nov20 3:23.69 /usr/sbin/syslogd
root 48299 0.0 0.0 4399372 1296 s001 R+ 5:09pm 0:00.00 ps aux
root 48294 0.0 0.0 4491800 4988 s001 Ss 5:09pm 0:00.08 login -pfl bronwen /bin/bash -c exec -la zsh /bin/zsh
_www 48293 0.0 0.0 4920324 1320 ?? S 5:09pm 0:00.00 /usr/local/opt/httpd/bin/httpd -k restart
bronwen 48284 0.0 0.0 5180944 13176 s000 SN 5:08pm 0:00.04 php playgame.php
bronwen 48282 0.0 0.0 5304848 13280 s000 SN 5:10pm 0:00.05 php playgame.php

And then I can pick up the process ID from the 2nd column, and use that to kill the relevant & problematic process

% kill 48284

But that’s tedious, and also prone to user error. (It’s too easy to get the wrong process.)

So I can use grep to find all the revelent processes. This command will list all the processes which match playgame.

% ps aux | grep playgame | grep -v grep

bronwen 48284 0.0 0.0 5180944 13176 s000 SN 5:08pm 0:00.04 php playgame.php
bronwen 48282 0.0 0.0 5304848 13280 s000 SN 5:10pm 0:00.05 php playgame.php
bronwen 48497 0.0 0.0 4408572 796 s001 R+ 5:14pm 0:00.00 grep playgame

But that includes the grep command I’ve just run and I don’t want it. grep -v to the rescue (v=inVert)

% ps aux | grep playgame | grep -v grep

bronwen 48284 0.0 0.0 5180944 13176 s000 SN 5:08pm 0:00.04 php playgame.php
bronwen 48282 0.0 0.0 5304848 13280 s000 SN 5:10pm 0:00.05 php playgame.php

Okay. We’re getting there. I’ve isolated the problem processes. Now I want to isolate the process ID from the second column.

awk is a command designed for pattern matching, and data extraction. It’s widely used to reformat the output of other commands, and as such is worth its weight in gold. (Can a command be worth its weight? Yes, it can.)

This command will output the second column:

% ps aux | grep playgame | grep -v grep | awk '{print $2}'

48284
48282

Now I want to kill those processes. xargs kill will read the input (in our case from the pipe), make a command consisting of kill (where items are whatever it read from the input), and then execute the command created.

% ps aux | grep playgame | grep -v grep | awk '{print $2}' | xargs kill

This will kill processes with ID 48282 and 48284.

Mission accomplished.