Logo

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 tells pkill 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:

  1. ps aux: Lists all running processes.
  2. grep -E 'your_regex_pattern': Filters the process list by your regex.
  3. awk '{print $2}': Prints the PID (process ID) from the second column of the ps output.
  4. xargs kill -9: Sends a SIGKILL (-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 just kill (default signal is TERM) or pkill -TERM -f 'pattern'.

Examples

  1. Using pkill -f:

    # Kills any process whose command line matches 'java.*MyServer' pkill -f 'java.*MyServer'
  2. 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:

  1. Grokking the Coding Interview: Patterns for Coding Questions
    Master common patterns essential for technical interviews and problem solving.

  2. 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.

CONTRIBUTOR
TechGrind