[Bash] Kill all processes matching the given pattern

Linux & MacSystem Command

Recently I am in need of shutting down multiple java processes all at once in the development environment, so I finally came up with a bash script to obtain all java process ids and kill them.

ps -aux | grep "java" | grep -v "grep" | awk '{print $2}' | while read -r pid ; do
    echo "Shutting down PID: $pid"
    kill $pid
done

Details:

  1. ps -aux: List all processes。
  2. grep "java": Filter all processes containing java in the commands.
  3. grep -v "grep": Surpress the current shell scipt process.
  4. awk '{print $2}': Preserve process id in column 2 and delete all other columns.
  5. Loop through all pids and kill them.

Leave a Reply

Your email address will not be published. Required fields are marked *