Graceful way to kill process

killprocesssearch

After my bash script is done with the selenium server, the script kills it like this:

kill `ps -ef | grep selenium | awk '{ print $2 }'`

While this works and it does kill the selenium script, it also tries to kill the process for grep selenium So by the time that process number gets back to the kill command, the process is gone, so it ends up generating an error message. (In other words: it ends up killing two processes, one of them is the real selenium server, the other is a fleeting process that is a side-effect of how I'm doing this command.)

Is there a more graceful way to kill the process, that doesn't have this unintended side-effect?

(FWIW one idea I had: this same script starts up selenium earlier in the script, so maybe if there was a way I could capture the PID when I start up selenium, I could just keep that and kill it directly, instead of grepping for the process ID. The problem is, I don't know how to get that PID, how to use a variable to keep it and how to reference it later in the script. But is that a better way to go about it?)

Best Answer

Try to use pkill selenium if neither this, nor one of the others work you can keep using your method with another pipe sequence such as

kill `ps -ef|grep -i selenium| grep -v grep| awk '{print $2}'`