Home > other >  Why does my kill .sh script sometimes not kill the intended processes?
Why does my kill .sh script sometimes not kill the intended processes?

Time:02-10

I have a .sh script that calls a number of other .sh scripts and tee's them into log files, and runs them in the background:

startMyProg.sh:

#!/bin/bash

./MyProg1.sh | tee /path/to/log/prog1_`date  \%Y\%m\%d_\%H\%M\%S`.log &
./MyProg2.sh | tee /path/to/log/prog2_`date  \%Y\%m\%d_\%H\%M\%S`.log &
./MyProgN.sh | tee /path/to/log/progN_`date  \%Y\%m\%d_\%H\%M\%S`.log &

I also have a simple helper script that will kill all the processes with MyProg in the name:

killMyProgs.sh:

#!/bin/bash
kill $(ps aux | grep MyProg | awk '{print $2}')

This system generally works, but occasionally the killMyProg.sh script doesn't kill the processes that it finds using the ps|grep|awk pattern. The part that really throws me for a loop is, when I face an instance where the .sh script doesn't kill the processes, I can call kill $(ps aux | grep MyProg | awk '{print $2}') directly from the command line and it will do what I expect it to! Is there something that I'm missing in my approach? Are there any useful debugging techniques that can help me figure out why my .sh script doesn't kill the processes but calling the exact command from the command line does?

A couple of details that may be relevant: the "./MyProgN" scripts are calls to to start the same MyProg.jar file with different inputs. So the ps|grep of "MyProg" shows both the .sh scripts AND the java applications that they started and kills all of them.

Using RHEL7

CodePudding user response:

Test few time to run:

 ps aux | grep MyProg | awk '{print $2}'

You will notice that sometimes the grep command comes before MyProg

And sometimes grep command comes after MyProg (depnding on the pid).

Because grep command is listed as well in ps aux.

Therefore sometimes your script is killing the first grep command instead of your command.

The easiest solution is to use pkill command.

  pkill -9 -f MyProg
  • Related