I detailed the open
command in the last Shell Tricks post, so I thought I’d go over some tricks for doing the opposite next: closing and quitting apps.
The first thing I’ll mention is a shell script from Jon Stovell called quit
. You can download it from his freeware page. It uses AppleScript (with some great logic) to “nicely” quit any application. I’ve mentioned it before, as well as tricks for adding Bash completion to it.
Second, I’ll point out my fk
shell command. The first version was handy, and I made some additions shortly after. I have a new version for you today that incorporates the quit
command.
First, you need the fp
(find processes) command, which gives you a case-insensitive, partial title search for running processes (you can add both of these to your .bash_profile
):
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
}
And here’s the revised fk
command. Give it part of a process or app name and it will give you a menu of all matches (case-insensitive). Cancel the menu with “q” or enter a number. If the process is a Mac app, it will use quit, otherwise it will kill
the specific process chosen.
Note that you need the quit script in /usr/local/bin (or edit the fk
function to match your own location).
# build a menu of processes matching (case-insensitive, partial) first parameter
# now automatically tries to use the `quit` script if process is a Mac app <http://jon.stovell.info/personal/Software.html>
fk () {
local cmd OPT
IFS=$'\n'
PS3='Kill which process? (q to cancel): '
select OPT in $(fp $1); do
if [[ $OPT =~ [0-9]$ ]]; then
cmd=$(ps -p ${OPT##* } -o command|tail -n 1)
if [[ "$cmd" =~ "Contents/MacOS" ]] && [[ -f /usr/local/bin/quit ]]; then
echo "Quitting ${OPT%%:*}"
cmd=$(echo "$cmd"| sed -E 's/.*\/(.*)\.app\/.*/\1/')
/usr/local/bin/quit -n "$cmd"
else
echo "killing ${OPT%%:*}"
kill ${OPT##* }
fi
fi
break
done
unset IFS
}
Now you have the counterpart(s) to OS X’s open
command. Enjoy!
Ryan Irelan has produced a series of shell trick videos based on BrettTerpstra.com posts. Readers can get 10% off using the coupon code TERPSTRA
.