kill all processes of a user except a few in linux

Kinda hackerish:

ps -U tim | egrep -v "ssh|screen" | cut -b11-15 | xargs -t kill

this will kill everything but any ssh or screen processes. Here are the commands explained:

  • ps -U tim -- will obviously, list every process from the user tim
  • egrep -v "ssh|screen" -- will remove lines with ssh or screen processes
  • cut -b11-15 -- will cut the data in columns 11-15 (typically that's where the PID is located
  • xargs -t kill -- will pass all the process ID's to the kill command

You can also use awk, if you're more used to that.

ps -U tim | egrep -v "ssh|screen" | awk '{print $2}' | xargs -t kill

Nothing built in that I'm aware of. You could create a script like this:

#!/bin/bash
ps ux | sed -e '/bash/d' -e '/screen/d' | awk '{print $2}' | while read process
do 
  kill $process
done

If there were any other processes you wanted to avoid killing you would just need to add more

-e '/processname/d'

entries to the sed portion. There's probably a cleaner way to handle it, but this will work.


If you're killing all your procs a lot, you might want to investigate why you need to do that... but hey, this is all about doing things, not about not doing things.

One easy solution would be to use two userIDs... one for screen and your SSH connection, and the other one for all the processes you'll at some point want to kill off.

This is beyond "hackerish" and into just plain "hack" but it has an added advantage in that any OTHER programs you run as the "connect" user won't get killed when you kill off the other procs. This could include "tails" of error logs and things like that which you might WANT to have left around.

Hope this helps!


Try:

ps aux | grep ^$LOGNAME | egrep -v 'ps aux|-bash|sshd' | awk '{ print $2 }' | xargs kill -9; ps aux | grep $LOGNAME