Monday, November 22, 2010

Shell Script to Terminate Apps

I was learning unix commands and regular expression on the mac sitting on office desk, and did a little exercise: a shell script that terminates a running application given the name of the app.

The shell script goes like this:

#!/bin/sh

ps auxc | grep -i "$1" | awk "{print $2}" | xargs kill

That was it. Now let me explain.

The line is composed of four individual commands piped together with the piping operator "|".

The first command, "ps auxc" lists all the running processes. The output of this command is piped into the second command, "grep -i "$1"", which takes the first argument of the script, i.e. the name of the Application that you want to terminate, and returns the line that contains that name. The third command scans that line, and returns the second field in the line, which is the process ID of the application to be terminated. Finally, the last command, "xargs kill" takes the process ID generated above as an argument, and passes it to the termination program "kill", to terminate the application.

No comments: