How to kill all process with given name?

I run command ps -A | grep <application_name> and getting list of process like this:

19440 ?        00:00:11 <application_name>
21630 ?        00:00:00 <application_name>
22694 ?        00:00:00 <application_name>

I want to kill all process from the list: 19440, 21630, 22694.

I have tried ps -A | grep <application_name> | xargs kill -9 $1 but it works with errors.

kill: illegal pid ?
kill: illegal pid 00:00:00
kill: illegal pid <application_name>

How can I do this gracefully?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

pkill -f 'PATTERN'

Will kill all the processes that the pattern PATTERN matches. With the -f option, the whole command line (i.e. including arguments) will be taken into account. Without the -f option, only the command name will be taken into account.

See also man pkill on your system.

Method 2

The problem is that ps -A | grep <application_name> | xargs -n1 returns output like this

19440
?
00:00:11
<application_name>
21630
?
00:00:00
<application_name>
22694
?
00:00:00
<application_name>

You can use awk to a get first a column of ps output.

ps -A | grep <application_name> | awk '{print $1}' | xargs -n1

Will return list of PIDs

19440
21630
22694

And adding kill -9 $1 you have a command which kills all PIDs

ps -A | grep <application_name> | awk '{print $1}' | xargs kill -9 $1

Method 3

killall can do that.

$ killall application_name

Method 4

pkill sends SIGTERM in default, and in my case pkill -f <some_pattern> did’nt kill my processes. I recommend below command for such cases, which worked perfectly for me!

kill -9 $(pgrep -f somepattern)

I also recommend to see which processes match before running kill command

pgrep -af somepattern

Method 5

My approach is similiar to @Łukasz D. Tulikowski‘s. Instead of using grep <application_name>; I have used grep "[a]pplication_name", which does not match with its own process command line.

The square bracket expression is part of the grep‘s character class pattern matching. (Reference).


You can use awk to a get first a column of ps output.

ps -A | grep "[a]pplication_na" | awk '{print $2}' | xargs -n1

Will return list of PIDs

7644
407
406

Later adding kill -9 $1 you have a command, which kills all PIDs

kill -9 $(ps aux | grep "[a]pplication_na" | awk '{print $2}')


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x