fk: a useful bash function

[Tweet : ADN : nvALT]

This is a function from my OS X .bash_profile. ‘fk’ is short for Find and Kill, and it lets you do a quick search of your running processes for a case-insensitive partial match of the first parameter passed to it. It’s useful for quickly finding a process without worrying about its capitalization or full spelling, and without having to sift through (or manually grep) a long ps ax list.

fp () { #find and list processes matching a case-insensitive partial-match string
		ps Ao pid,comm|awk '{match($0,/[^\/]+$/); print substr($0,RSTART,RLENGTH)": "$1}'|grep -i $1|grep -v grep

fk () { # build menu to kill process
    PS3='Kill which process? '
    select OPT in $(fp $1) "Cancel"; do
        if [ $OPT != "Cancel" ]; then
            kill $(echo $OPT|awk '{print $NF}')
    unset IFS

On OS X (and similar Linux systems), you should have a file in your home folder (cd ~) called .bash_profile. Just copy and paste this code at the bottom of that file, and then run source ~/.bash_profile in Terminal. Now (and every time you log in) you can run fk process, where process is a partial name of a running application or UNIX process. You’ll get a menu with the matches, and you can kill a specific process by typing its number at the prompt. The last option is always “Cancel,” which will terminate the command without taking any action. I’d love to hear about any improvements you make to this code… I’m far from a Bash pro.

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.