How to find and kill a process in one line using bash and regex?
A common way to find and kill processes in one line using bash (with a regex-like pattern) is to use pkill
(or pgrep
+ kill
). For example:
pkill -f 'pattern'
-f
tellspkill
to match against the entire command line (not just the process name).'pattern'
can be a regular expression that matches the process(es) you want to kill.
If you prefer a pipeline approach with grep
and awk
, you can do something like:
ps aux | grep -E 'your_regex_pattern' | awk '{print $2}' | xargs kill -9
Explanation:
ps aux
: Lists all running processes.grep -E 'your_regex_pattern'
: Filters the process list by your regex.awk '{print $2}'
: Prints the PID (process ID) from the second column of theps
output.xargs kill -9
: Sends aSIGKILL
(-9
) to each PID from the pipeline.
Note: Use
-9
with caution; it force-kills processes and doesn’t allow them to clean up. If a gentler approach is acceptable, consider using justkill
(default signal isTERM
) orpkill -TERM -f 'pattern'
.
Examples
-
Using
pkill -f
:# Kills any process whose command line matches 'java.*MyServer' pkill -f 'java.*MyServer'
-
Using
ps
+grep
+awk
+xargs
:# Kills processes that match 'my_script.*arg' ps aux | grep -E 'my_script.*arg' | awk '{print $2}' | xargs kill -9
Bonus: Level Up Your Bash, Regex, and System Skills
For deeper command-line proficiency and broader system knowledge, consider the following courses from DesignGurus.io:
-
Grokking the Coding Interview: Patterns for Coding Questions
Master common patterns essential for technical interviews and problem solving. -
Grokking System Design Fundamentals
Learn core concepts for designing scalable systems—vital for any DevOps or backend-heavy role.
For personalized feedback, check out Mock Interviews (Coding Mock Interview or System Design Mock Interview) with ex-FAANG engineers. You can also find free tutorials on the DesignGurus.io YouTube channel.