How to kill a bunch of processes which executed with almost same command ?

Scenario

Sometimes we need to manually terminate the process. If not killing too many processes, it is easy to find the pid and kill it. But what if there are a bunch of processes that need to be terminated? Today I encountered such a problem, started a lot of python process, but the result can not stop.

gkill Solution

add below function to your bash profile, then source the profile

function gkill() {
    ps -ef | grep ${1} | grep -v grep | awk '{print $2}' | xargs --no-run-if-empty kill -9
}

Then you can kill all processes that matched your serach pattern via gkill command.

gkill <search content>

Extended knowledge

The commands related to the termination process are:

  • ps: report a snapshot of the current process
  • kill: send a signal to a process
  • killall: kill process by name
  • pkill: View or issue process signals based on name and other attributes
  • skill: send a signal or report the process status
  • xkill: destroy a client program according to X resources
  • xargs --no-run-if-empty, very useful if args from pipe are empty

pgrep

pgrep is a tool to query the process by the name of the program, generally used to determine whether the program is running. This tool is often used in server configuration and management. Usage: pgrep parameter option program name.

grep

grep (global search regular expression (RE) and print out the line, comprehensive search regular expression and print out the line) is a powerful text search tool, it can use regular expressions to search for text, and print the matching line come out. Unix's grep family includes grep, egrep, and fgrep.

In simple terms, pgrep is to query the running status of the program, and grep is to search for content.

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe