Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want a script which kills the instance(s) of ssh which are run with the -D argument (setting up a local proxy).

Manually, I do ps -A | grep -i ssh, look for the instance(s) with -D, and kill -9 {id} each one.

But what does that look like in bash script form?

(I am on Mac OS X but will install any necessary commands via port)

share|improve this question
See pgrep and pkill alternatives on mac os x?. pgrep and pkill are commands to reliably find or kill processes by name under Solaris and Linux. – Gilles Jan 12 '11 at 8:12
up vote 21 down vote accepted

Run pgrep -f "ssh.*-D" and see if that returns the correct process ID. If it does, simply change pgrep to pkill and keep the same options and pattern

Also, you shouldn't use kill -9 aka SIGKILL unless absolutely necessary because programs can't trap SIGKILL to clean up after themselves before they exit. I only use kill -9 after first trying -1 -2 and -3.

share|improve this answer
you should redefine kill as a for loop that does kill -i for each i ;) – Seamus Jan 12 '11 at 14:29
pgrep is not native on OSX, you have to get it from a third party. The previous thread on the topic has proposals and alternatives. – Gilles Jan 12 '11 at 21:21
man alive, the more I use 'nix, the more I love it :) thanks for this! – javamonkey79 Nov 29 '11 at 19:19
pgrep and pkill are available in OS X 10.8 (Mountain Lion) and above. apple.blogoverflow.com/2012/07/… – Peter Hanley Apr 25 '14 at 18:24

You can leverage the proc file system to gather the information. For example:

for proc in $(grep -irl "ssh.*-D" /proc/*/cmdline | grep -v "self"); do if [ -f $proc ]; then cat $proc && echo ""; fi; done

It's not perfect, you'll want a more exclusive regex (especially if you are killing processes) but echo $proc | awk -F'/' '{ print $3 }' will show you the PID of the process(es).

share|improve this answer
OSX doesn't have /proc. And there's already a robust tool to do this out there, called pgrep (available natively at least on Solaris and Linux). – Gilles Jan 12 '11 at 21:20


kill `pgrep -f "ssh.*-D"`
share|improve this answer
I think this is equivalent to pkill – Michael Mrozek Jan 18 '11 at 14:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.