How to Kill a Process Based on Part of the Process Name

How to Kill a Process Based on Part of the Process Name

Category : How-to

Get Social!

This is a small, handy snippet to kill a Linux process based on matching a string from the ps command output.

For example, we may want to kill the mongodb process based on matching just the string mongo.

We would use the below command, consisting of ps and grep to get the process we would like to kill.

ps aux | grep mongo
mongodb   1025  0.7  7.9 5076284 39120 ?       Sl   Jul08  10:16 /usr/bin/mongod --config /etc/mongodb.conf
root     11873  0.0  0.1  11748   916 pts/0    S+   19:07   0:00 grep --color=auto mongo

We need to change the grep slightly, to stop the actual grep command process that we just ran from returning. We can add [] around part of the matching string to stop the process from being matched exactly as it will be parsed as a pattern, and not a literal string.

ps aux | grep mong[o]
mongodb   1025  0.7  7.9 5076284 39120 ?       Sl   Jul08  10:16 /usr/bin/mongod --config /etc/mongodb.conf

It doesn’t matter where on the string you add the brackets, as long as they are there somewhere.

Using awk we can now filter the results line to only print out the pid of the mongodb process.

ps aux | grep mong[o] | awk {'print$2'}
1025

Finally, we need to wrap all of this with the kill statement to remove the process. Be careful here as this will immediately kill the process with no warning or confirmation. This is just an example, it’s never a good idea to forcefully kill the mongodb process!

kill -9 `ps aux | grep mong[o] | awk {'print$2'}`

And that’s it, the mongodb process is dead!


Visit our advertisers

Quick Poll

Are you using Docker.io?

Visit our advertisers