Kill a process in Linux in one line

Kill a process in Linux in one line

There is a program running with the command python src/main.py (maybe in background). Now you want to find its PID and kill it in one command line.

With pkill

pkill -f "python src/main.py"

By default, pkill / pgrep search for the process name (in this example, python) only. -f implies a full pattern matching, in other words, the whole command line triggered the process.

If you wish to match the program name only, drop the -f flag. For examples:

pkill chrome
pkill java

Note that pkill will send the signal (SIGTERM by default, or specified with -signal signal) to ALL found processes. To list for the matched process, replace pkill with pgrep.

Other useful flags for the pgrep/ pkill family:

For pgrep only:

  • -c / --count: print number of matches. Note: if nothing matches, zero is printed and a non-zero exit code is returned.
  • -d / --delimiter followed by a string to specify the delimiter among results. The default delimiter is a newline.
  • -l / --list-name: list the process name following each PID.
  • -a / --list-full: list the full command line following each PID.
  • -v / --inverse: negate the matching. This is not available in pkill to avoid accidental pkills.

For pkill only:

  • --signal <sig> or -<sig>: signal to send. For example: -9 (SIGKILL) is used to force killing.
  • -e / --echo: show what is killed.

Shared between pkill and pgrep.

  • -i / --ignore-case.
  • -n / --newest: select the most recently started.
  • -o / --oldest: select the least recently started.
  • -O / -Older <seconds>: older than <seconds> seconds.
  • -x / --exact: match exactly.
  • -P / --parent <PPID,...>: match whose parent matches the given PPIDs.
  • -u / --euid <ID,...>: match effective user IDs. Both numbers and text can be used.
  • -U / --uid <ID,...>: match real user IDs. Both numbers and text values can be used.
  • -g / --pgroup <pgid,...>: match group IDs.
  • -G / --group <gid,..>: match real group IDs.

With pure ps command

For those who are familiar with more traditional commands. Use:

kill -9 $(ps aux | grep "[p]ython src/main.py" | tr -s ' ' | cut -d ' ' -f 2)

Or

kill -9 $(ps aux | grep "[p]ython src/main.py" | awk '{print $2}')

Explanation:

  • grep "[p]ython...": the [p] trick is used to ignore the grep command itself.
  • tr -s ' ': squeeze the specified character (' ') if repeated.
  • cut -d ' ':  delimiter for field (column) separation. The default character is tab.
  • cut -f 2: select the second field.
  • awk '{print $2}': print the second field.

Note: this command kills all founded (multiple) processes. If no process founded, the error message kill: not enough arguments is printed with a non-zero error and no side effects occur.

Buy Me A Coffee