Linux – kill all processes of a user except a few in linux

killlinuxprocess

I was running some processes under a screen session on a remote server. When I tried to kill all those processes by:

pkill -U tim

all my processes are killed including those I don't want to kill (i.e. the screen and ssh connection).

Is there a way to kill all my processes except the screen and ssh connection?

Best Answer

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
Related Question