July 25, 2007

FMT Is My Friend

How many times have you been looking for an obscure shell command to do something, haven't found it, and then use perl or python do work around that problem? It has happened to me several times, but this time my search for an obscure shell command that did exactly what I wanted was successful. That command was fmt. One of my tests consists of starting up a product, waiting for it to get into a steady state, then killing one of the supporting processes, and then running tests to see how it handles the requests that I send it. Pretty simple right? For non-software people out there it is kind of like taking a table (with 4 legs), sawing off one of the legs, and then load testing it to see when and where it fails, kind of. The only interesting and non product specific line of code from the shell script that I can print here is this:

kill -9 `ps -ef | grep SomeProcess | awk '{print $2}' | fmt`

This line basically does a ps command, filters out the term SomeProcess, then filters out the process ID (I usually get 3 process IDs as output), and then puts them all as one string with white space in between them using fmt. Then the kill command kills off all of those processes. So in a nutshell it kills off all the processes that I want killed. I guess it is debatable as to whether or not -9 is needed, but I'm putting it in there just to be safe. But it was fairly random that I found it and was able to apply the fmt command. Officially fmt does the following:

fmt is a simple text formatter that fills and joins lines to produce output lines of (up to) the number of characters specified in the -w width option. The default width is 72. fmt concatenates the inputfiles listed as arguments. If none are given, fmt formats text from the standard input.

In my case it takes my three process IDs output by the `ps -ef | grep SomeProcess | awk `{print $2]`` command:

20309
21417
87362

and slaps them together -> 20309 21417 87362 so that you can kill them all with one kill command. So the final command looks like this:

kill -9 20309 21417 87362

wam bam thank you mam. Simple shell scripting kept simple and effective. I learned today that fmt is my friend.

Posted by troutm8 at July 25, 2007 02:54 PM