I am not a Linux newbie, but neither am I an expert. So, I sometimes tend to come across some really cool stuff and I just have to share.

Here is the story. We use this application at work (I won’t point any fingers :)) which tends to run as a whole lot of processes when it starts up, and these processes don’t all have the same parent process either. Once in a while this application can get into a bad state where you have to manually kill all the processes to restart everything. Now as you might imagine this can be a bit of a pain since there are quite a few processes even if you only count the parents.

Here is where some bash magic comes to the rescue. Luckily for us, this application runs as a separate Linux user so all the processes have the same user id and we’re able to use the following command to kill everything in one fell swoop.

ps -ef | grep ^1002 | cut -c 5-15 | sudo xargs kill<br />

Here is a quick rundown of what it does:

  • the ps command is obvious, we get the processes that are currently active
  • we pipe the output to grep in order to find all the lines that begin with a particular id (this is the id of the user that runs the application)
  • we then pipe the output of that to the cut command to pull out characters 5 to 15 of every line (i.e. the process id will live in that character range)
  • we then pipe the output of that to xargs which lets us use each line of that output as an argument to the_ kill_ command, thereby killing all those processes (the sudo bit is really optional and you would use it only if your current user didn’t have permission to kill the processes)

Update: As Sam pointed out in the comments below kill -9 should only ever be used as a last resort as it will create ‘orphaned shared memory segments’ and is therefore best avoided if possible

I don’t know about you, but I thought that was pretty cool :). The only side-effect is that all processes owned by that particular user will get killed (i.e. if you have a shell opened as that user).

I wonder if there is an easier way of doing this with bash? And it would also be great if we didn’t have to kill all processes owned by a user, but rather could mass-kill a bunch of processes based on some other criteria. If anyone is a bash expert, feel free to supply some tips :).

Update: Apparently, according to the comments, there are a number of way of doing this, using either a shorter pipeline or even just one command that would even let you pick particular processes based on criteria _(e.g. pkill)_. Have a look through the comments for details. Thanks to all the commenters for the great feedback!