[linux] How to kill all processes with a given partial name?

I want to kill all processes that I get by:

ps aux | grep my_pattern

How to do it?

This does not work:

pkill my_pattern

This question is related to linux bash posix

The answer is


If you judge pkill -f PATTERN a bit too dangerous, I wrote ezkill a bash script that prompt you to choose which processes amongst those that match the PATTERN you want to kill.


it's best and safest to use pgrep -f with kill, or just pkill -f, greping ps's output can go wrong.

Unlike using ps | grep with which you need to filter out the grep line by adding | grep -v or using pattern tricks, pgrep just won't pick itself by design.

Moreover, should your pattern appear in ps's UID/USER, SDATE/START or any other column, you'll get unwanted processes in the output and kill them, pgrep+pkill don't suffer from this flaw.

also I found that killall -r/ -regexp didn't work with my regular expression.

pkill -f "^python3 path/to/my_script$"

man pkill


Found the best way to do it for a server which does not support pkill

kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')

You do not have to loop.


You can use the following command to:

ps -ef | grep -i myprocess | awk {'print $2'} | xargs kill -9

or

ps -aux | grep -i myprocess | awk {'print $2'} | xargs kill -9

It works for me.


Kill all processes matching the string "myProcessName":

ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9

Source: http://www.commandlinefu.com/commands/view/1138/ps-ef-grep-process-grep-v-grep-awk-print-2-xargs-kill-9

What's this code doing?

The ps -ef produces a list of process id's on the computer visible to this user. The pipe grep filters that down for rows containing that string. The grep -v grep says don't match on the process itself doing the grepping. The pipe awk print says split the rows on default delimiter whitespace and filter to the second column which is our process id. The pipe xargs spins up a new process to send all those pid's to kill -9, ending them all.

The above code is bad, dangerous, ugly and hackish for several reasons.

  1. If the code being force-ended is doing any database ops or secure transactions with low probability race conditions, some fraction of a percent of the time, atomicity of that transaction will be wrecked, producing undefined behavior. kill -9 takes no prisoners. If your code is sensitive to this, try replacing the xargs kill part with a transmitted flag that requests a graceful shutdown, and only if that request is denied, last-resort to kill -9

  2. There's a non zero possibility that you will accidentally end the operating system or caused undefined behavior in an unrelated process, leading to whole system instability because ps -ef lists every possible process that could exist, and you can't be sure some weird 3rd party library shares your process name, or that in the time between read and execute kill -9, the processid had changed to something else, and now you've accidentally ended some random process you didn't intend to.

But, if you understand the risks and control for them with very unique names, and you're ok with a few dropped transactions or occasional corruption in data, then 99.9% of the time yer gonna be fine. If there's a problem, reboot the computer, make sure there aren't any process collisions. It's because of code like this that makes the tech support script: "Have you tried restarting your computer" a level 5 meme.


you can use the following command to list the process

ps aux | grep -c myProcessName 

if you need to check the count of that process then run

ps aux | grep -c myProcessName |grep -v grep 

after which you can kill the process using

kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }') 

If you need more flexibility in selecting the processes use

for KILLPID in `ps ax | grep 'my_pattern' | awk ' { print $1;}'`; do 
  kill -9 $KILLPID;
done

You can use grep -e etc.


I took Eugen Rieck's answer and worked with it. My code adds the following:

  1. ps ax includes grep, so I excluded it with grep -Eiv 'grep'
  2. Added a few ifs and echoes to make it human-readable.

I've created a file, named it killserver, here it goes:

#!/bin/bash
PROCESS_TO_KILL=bin/node
PROCESS_LIST=`ps ax | grep -Ei ${PROCESS_TO_KILL} | grep -Eiv 'grep' | awk ' { print $1;}'`
KILLED=
for KILLPID in $PROCESS_LIST; do
  if [ ! -z $KILLPID ];then
    kill -9 $KILLPID
    echo "Killed PID ${KILLPID}"
    KILLED=yes
  fi
done

if [ -z $KILLED ];then
    echo "Didn't kill anything"
fi

Results

?  myapp git:(master) bash killserver
Killed PID 3358
Killed PID 3382
Killed
?  myapp git:(master) bash killserver
Didn't kill anything

Sounds bad?

 pkill `pidof myprocess`

example:

# kill all java processes
pkill `pidof java`

You can use the following command to

kill -9 $(ps aux | grep 'process' | grep -v 'grep' | awk '{print $2}')

Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.

killall -r my_pattern

If you do not want to take headache of finding process id, use regexp to kill process by name. For example, to kill chrome following code will do the trick.

killall -r chrome


This is the way:

kill -9 $(pgrep -d' ' -f chrome)

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to posix

How to make parent wait for all child processes to finish? Kill all processes for a given user What is the proper #include for the function 'sleep()'? What is /dev/null 2>&1? How to kill all processes with a given partial name? What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()? How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`? Converting year and month ("yyyy-mm" format) to a date? CRON job to run on the last day of the month Checking if a file is a directory or just a file