Shell – killing processes automatically

awkkillprocessshell-script

I need to kill all processes in a certain shell, excluding certain processes.

For example, sh, which is my shell, and the command.

This is what is currently in my shell right now.

rcihp146 :/home/msingh2> ps
   PID TTY       TIME COMMAND
  8880 pts/258   0:00 ps
  5908 pts/258   0:00 sh

But if there are some extra processes I would like to kill all of them, excluding the above two.

I tried a one-liner for this purpose and it didn't work:

rcihp146 :/home/msingh2> ps | awk '{system("kill -9 $1")}'
sh: kill: The number of parameters specified is not correct.
sh: kill: The number of parameters specified is not correct.
sh: kill: The number of parameters specified is not correct.
sh: kill: The number of parameters specified is not correct.

… but it works if I only give a specific pid like below:

 rcihp146 :/home/msingh2> ps | awk '{system("kill -9 23456")}'

I need to exclude two or three process (like ps, sh) from being killed.

Is there any way to do this?

Best Answer

Of course the one liner you wrote won't work since the $1 is inside the quotes. Try this:

ps| gawk '{ if ($4 != "COMMAND" && $4 != "sh" && $4 != "ps") system("kill -KILL "$1) }'

Have fun but use it with caution. I generally don't like system commands in gawk, certainly not the "kill" command.

Related Question