28

I need to kill a process that contains myName in its description. Currently I'm doing:

ps -ax |grep myName
I see PID
kill -9 PID

How can I do the same with one command without entering the PID?

kos
  • 35,891
vico
  • 4,527
  • 21
  • 58
  • 87
  • Do be aware that using -9 sends a SIGKILL signal, which means that no cleanup will be done by the process, normally SIGTERM is a safer signal to send, but it obviously depends on your needs. – Arronical Apr 22 '16 at 10:02
  • See the first answer to the linked duplicate, pkill for example allows to kill processes which match a string / regular expression. – kos Apr 22 '16 at 14:21

5 Answers5

56

If myName is the name of the process/executable which you want to kill, you can use:

pkill myName

pkill by default sends the SIGTERM signal (signal 15). If you want the SIGKILL or signal 9, use:

pkill -9 myName

If myName is not the process name, or for example, is an argument to another (long) command, pkill (or pgrep) may not work as expected. So you need to use the -f option.

From man kill:

-f, --full
              The pattern is normally only matched against the  process  name.
              When -f is set, the full command line is used.
NOTES
The process name used for matching is limited to the 15 characters present
   in the output of /proc/pid/stat.  Use the -f option to match  against  the
   complete command line, /proc/pid/cmdline.

So:

pkill -f myName

or

kill -9 $(pgrep -f myName)
Ron
  • 20,638
12

With a command's name use:

pkill -9 myscript

If you are looking for a string in the command line:

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

I have to warn you: the above command can send a SIGKILL signal to more than one process.

Jay jargot
  • 526
  • 2
  • 6
5

There are two very neat commands pgrep and pkill that allow entering search term or part of the command name , and it will either provide the PID(s) of the process or (in case of pkill) kill that process.

$ pgrep -f firefox                                                             
23699

Running the same command with pkill and -f flag will close all the firefox windows.

The -f flag is needed specifically to search through the full command-line of a process.

Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
4

With pkill and sending signal 9, you can kill process by name:

sudo pkill -9 myName
earthmeLon
  • 11,247
siz
  • 121
1

You could do a simple for loop over all the PID's associated with the specific process name, like this:

$ for i in $( ps ax | awk '/[m]yName/ {print $1}' ); do kill ${i}; done

This will kill all processes that contain the word: myName.

krt
  • 1,956
  • 15
  • 12