I want to write a shell script (.sh file) to get a given process id. What I’m trying to do here is once I get the process ID, I want to kill that process. I’m running on Ubuntu (Linux).
I was able to do it with a command like
ps -aux|grep ruby
kill -9 <pid>
but I’m not sure how to do it through a shell script.
Using
grepon the results ofpsis a bad idea in a script, since some proportion of the time it will also match the grep process you’ve just invoked. The commandpgrepavoids this problem, so if you need to know the process ID, that’s a better option. (Note that, of course, there may be many processes matched.)However, in your example, you could just use the similar command
pkillto kill all matching processes:Incidentally, you should be aware that using
-9is overkill (ho ho) in almost every case – there’s some useful advice about that in the text of the “Useless Use ofkill -9form letter “: