Bash script to find and kill a process with certain arguments

bashprocess

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)

Best Answer

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.

Related Question