19

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)

Ricket
  • 702
  • 3
  • 7
  • 14
  • See [pgrep and pkill alternatives on mac os x?](http://unix.stackexchange.com/questions/225/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 'SO- stop being evil' Jan 12 '11 at 08:12

3 Answers3

28

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.

SiegeX
  • 8,669
  • 3
  • 34
  • 23
  • 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](http://unix.stackexchange.com/questions/225/pgrep-and-pkill-alternatives-on-mac-os-x) has proposals and alternatives. – Gilles 'SO- stop being evil' 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. http://apple.blogoverflow.com/2012/07/interesting-new-unix-commandsbinaries-in-os-x-mountain-lion/ – 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 03 '18 at 09:27
2

Also,

kill `pgrep -f "ssh.*-D"`
Barun
  • 2,336
  • 20
  • 23
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).

Tok
  • 10,484
  • 2
  • 25
  • 12