17

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)

26

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.

  • you should redefine kill as a for loop that does kill -i for each i ;) – Seamus Jan 12 '11 at 14:29
  • 1
    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
  • It might be useful to add the -a flag to pgrep which makes it print not only the process id but also the command (including arguments). This way it is very easy to verify that only desired processes are matched. – luator Jul 3 '18 at 9:27
1

Also,

kill `pgrep -f "ssh.*-D"`
0

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).

  • 1
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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