836

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208
  • 13
    Is `my_pattern` simply a substring of the name, or does it contain any regex special characters? – Sven Marnach Jan 24 '12 at 12:48
  • I wasn't the one who closed it, but that is most likely the case. https://unix.stackexchange.com/ is the site for Unix and Linux related questions :) @ryanjdillon – Catlover Jun 24 '21 at 14:24

14 Answers14

1731

Use pkill -f, which matches the pattern for any part of the command line

pkill -f my_pattern

Just in case it doesn't work, try to use this one as well:

pkill -9 -f my_pattern
Kirby
  • 2,847
  • 2
  • 32
  • 42
dorsh
  • 23,750
  • 2
  • 27
  • 29
  • 10
    @Jayan: it's also quite indiscriminate in its killing. It's surprisingly easy to mishandle... – thkala Jan 24 '12 at 13:15
  • 1
    @Jayan: you are not going to convince me :-). I have been burnt way too many times by third-party scripts that insisted on using `pkill` - the most common mistake being the assumption that only one instance of each binary could exist at any given time. – thkala Jan 24 '12 at 13:30
  • 22
    For any Mac users who find this answer, like I did, the Mac equivalent is `killall -m my_pattern`. – Zev Eisenberg Aug 18 '14 at 22:25
  • @ZevEisenberg I found that `killall -m` does not match anything, but instead pkill does. They are both dangerous nuke though. – Vicary Dec 28 '14 at 09:45
  • Will "pkill -f my_pattern", kill multiple services to, or just one (first?) service that will match the pattern? – Johnny Mar 24 '15 at 10:00
  • @StasS - "pkill -f my_pattern" will terminate all matching processes. – MrWonderful Sep 10 '15 at 21:32
  • Doesn't work for me, I have to use the pipe (ps, grep and kill) to kill the specific PIDs of all the processes contain a pattern. – CodyChan Jan 28 '16 at 04:07
  • 4
    If you have a number of hanging processes which do not get killed use pkill -f -9 to mercilessly kill them – MacK Mar 16 '16 at 11:43
  • 47
    I recommend using `pgrep` first to verify what you are going to kill. You can use `pgrep -l` to see process names or `pgrep -a` to see full command lines. It uses the same flags as pkill. So in this case you could use `pgrep -fa my_pattern`. – studgeek Aug 29 '16 at 22:29
  • 1
    Flag `-f` means: search complete process name – Timo Nov 19 '17 at 18:54
  • 7
    I'd recommend adding the `-I` flag (capital `i`) so that it asks for confirmation before killing each matched process. Harder to shoot yourself in the foot that way. – agentofuser Jun 21 '18 at 14:18
  • Didn't work for me, only killed one out of four. The "One liner:" solution below worked. – Igor Vaschuk Oct 01 '18 at 19:05
  • if without `-f`, which part will it match? – ZhaoGang Sep 11 '19 at 08:17
  • 3
    What means "pattern". Regex? Please add examples. – mgutt Nov 21 '19 at 07:54
  • For the timorous there's also the `-x` option for pkill: "match exactly with the command name". Also on my machine there is no `-I` option. – mike rodent Jan 16 '20 at 21:52
  • To get this to kill processes that I start on boot (from a script in `/etc/init.d`), I needed to use `sudo pkill --signal SIGTERM -f process_name` – WNRosenberg Feb 13 '20 at 17:10
  • 1
    pkill -9 is better. – ABCD Jul 02 '20 at 10:51
  • 3
    @SmallChess is correct. I had 10 jobs that would only die using `pkill -9 -f my_pattern`. – WinEunuuchs2Unix May 21 '21 at 02:14
  • @WinEunuuchs2Unix man, you are the only right here =) – Kirby Sep 06 '21 at 20:24
  • I am getting "pkill: killing pid 47936 failed: Operation not permitted". It's ridiculous that kill is allowed but pkill needs ``sudo``. – Shaun Han Dec 29 '21 at 21:39
259

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

Why "ps pipe kill" from terminal is evil:

The Piping of integers you scraped from ps -ef to kill -9 is bad, and you should feel bad, doubly so if you're root or a user with elevated privileges, because it doesn't give your process a chance to cleanly shut down socket connections, clean up temp files, inform its children that it is going away or reset its terminal characteristics.

Instead send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved.

As a general principle we don't use Unix Railgun to trim the hedges. https://porkmail.org/era/unix/award.html#kill

Explanation of above command:

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.

Why ps pipe kill is bad, dangerous, ugly and hackish:

  1. There's a small possibility that you will accidentally end the operating system or cause undefined behavior in an unrelated process, leading to whole system instability because ps -ef lists thousands of processes, and you can't be sure some 3rd party process 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 ended some random necessary process unrelated to yours.

  2. 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

But, if you understand all the risks and control for them with unique names, and you're ok with a few dropped transactions or occasional corruption, 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. "A Rogue Robot scraped ps to find integers and sent those to kill -9, so reboot the computer to clear the problem.

Why not just use pkill which is easier?

The above gives me manual control because ps, grep, awk, kill and xargs are multi-platform standard. It gives full control to which regex engine to use, which part of the process name to match, handling case sensitivity and exception management.

pkill -f -e -c myProcessName

Does the same thing for me, but see man pkill has different behaviors, flags and regex engines between variants of Linux, Mac, Zune-Bash and my opensource router. So yes, put your 35000 Watt Unix-Railgun into the capable hands of pkill to trim the hedges. See what happens.

Grepping once

You can substitute the grep -v grep | with square brackets around the first letter of the command to kill, which does the same thing and prevents grep from grepping itself, for example:

ps -ef | grep '[m]yProcessName' | awk '{print $2}' | xargs -r kill -9

Why that works: https://askubuntu.com/questions/153419/how-does-this-tricky-bracket-expression-in-grep-work

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 2
    Just a slight modification, perhaps it is better to quote the process name: `ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9` Without quotes, only one of my background processes was killed on the first run. Running it again killed the rest. – Ali Haider Feb 14 '18 at 10:28
  • 1
    `-r` option doesn't exist on OS X, so it seems. – Danijel Oct 10 '19 at 09:41
  • @Eric-Leschinski `pkill -e` option is not available in CentOS7 that is to say with `pkill (procps version 3.2.8)` – SebMa Jul 12 '22 at 08:38
57

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.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • 4
    -1 You don't need a loop, you can just `kill -9 \`ps ax | awk '[m]y_pattern { print $1 }'\`` (note also the refactoring; see also my comment on @synthesizerpatel's answer). – tripleee Jul 09 '12 at 07:05
  • 11
    @tripleee No problem with your downvote, but you **do** realize, that the OQ was *"I want to kill all processes that I get by: ps aux | grep my_pattern"*, which I dutyfully accepted. – Eugen Rieck Jul 09 '12 at 07:26
  • Kill will kill all the processes in one go, you don't need a loop for that. If the `ps` returns three processes 123, 234, and 345, you can `kill 123 234 345` just like you can `rm` or `cat` multiple file arguments. – tripleee Jul 09 '12 at 07:49
  • @tripleee I ment removing the `grep` – Eugen Rieck Jul 09 '12 at 08:18
  • `for KILLPID in `ps ax | grep 'puma' | grep -v 'grep' | awk ' { print $1;}'`; do kill -9 $KILLPID; done` will remove the grep – Justin E Sep 14 '14 at 01:49
21

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 }') 
DocRattie
  • 1,392
  • 2
  • 13
  • 27
  • 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 }') – Nived Karimpunkara Jun 21 '16 at 07:15
17

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

killall -r my_pattern
Alex
  • 5,728
  • 5
  • 20
  • 20
8

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.

Warning: This project is no more maintained.

Valerio Bozz
  • 1,176
  • 16
  • 32
kraymer
  • 3,254
  • 1
  • 24
  • 32
8

You can use the following command to

kill -9 $(ps aux | grep 'process' | grep -v 'grep' | awk '{print $2}')
Alex Liu
  • 95
  • 1
  • 8
6

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

Kodiak
  • 5,978
  • 17
  • 35
ajaz
  • 89
  • 1
  • 2
  • 1
    You only need either `-r` _or_ `--regexp`, which are the short and the GNU long option, respectively. – BigSmoke Jan 10 '20 at 10:47
5

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.

Manrique
  • 2,083
  • 3
  • 15
  • 38
Magige Daniel
  • 1,024
  • 1
  • 10
  • 10
4

This is the way:

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

The pgrep searches for all processes related to chrome and returns them in a list separated by spaces.

This is passed to the kill application that can safely kill all the related chrome processes.

This is still dangerous, be careful.

mit
  • 11,083
  • 11
  • 50
  • 74
MadMad666
  • 955
  • 3
  • 11
  • 19
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Igor F. Feb 19 '20 at 13:40
  • first the pgrep search for all processes related to chrome and return them in a list separated by space. This is pass to the kill application that can safety kill all the related chrome processes. – MadMad666 Feb 09 '21 at 15:56
3

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.

mx0
  • 6,445
  • 12
  • 49
  • 54
Luis Lopes
  • 31
  • 3
  • 1
    Welcome to StackOverflow. Please use 4-space or tab indentation for your code lines so that they are formatted as code blocks. Best regards – YakovL Sep 08 '17 at 16:56
2

Sounds bad?

 pkill `pidof myprocess`

example:

# kill all java processes
pkill `pidof java`
1

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

Wis
  • 484
  • 7
  • 22
0

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
Meir Gabay
  • 2,870
  • 1
  • 24
  • 34