How do I kill all subprocesses spawned by my bash script?

I have a script that looks like this. Invoked with ./ start

if [[ "$1" == "start" ]]; then
  echo "Dev start script process ID: $$"

  cd /my/path1
  yarn dev &> /my/path/logs/log1.log &
  echo "started process1 in background"
  echo "Process ID: $!"
  echo "Logging output at logs/log1.log"
  sleep 2

  cd /my/path2
  yarn start:dev &> /my/path/logs/log2.log &
  echo "started process2 in background"
  echo "Process ID: $!"
  echo "Logging output at logs/log2.log"
  sleep 2

  cd /my/path2
  yarn dev &> /my/path/logs/log3.log &
  echo "started process3 in background"
  echo "Process ID: $!"
  echo "Logging output at logs/log3.log"
elif [[ "$1" == "stop" ]]; then
  killList=`ps  | grep node | awk '{print $1}'`
  if [[ $killList != "" ]]; then
      echo $killList | xargs kill
      echo  "Processes killed: $killList"
      echo "Nothing to stop"
  echo "Invalid argument"

When i run ps after I run this script, i can see a bunch of node processes (more than 3) that I assume has been started by the yarn dev commands. I want to run ./ stop and stop all the node processes that were spawned from my previous run of ./ start

How do I make this happen?

Asked By: Jay Pillai


You could get the list of processes directly spawned from that bash and send SIGTERM to them:

pkill -P $$

$$ is the process number of the current bash script.

Depending on how the signal is treated by the child processes, that might or not kill the grandchild processes (and so on, recursively).

So another way to do it is to get list the whole tree of processes starting at your bash and then kill them.

pstree -A -p $$ | grep -Eow "[0-9]+" | xargs kill

pstree outputs the tree (formatted for humans), grep extracts the process numbers and then you do what you need to do with them, for example running kill for each one.

Note that with the line above pstree will also list the grep and xargs processes, so you will have two No such process warnings from kill. Not sure if there is a race condition, that’s just a proof of concept. You can code the right side of the pipeline to deal with the list of processes properly, filter, etc.

Answered By: Eduardo Trápani