Okay, so I have a dilemma that I've been staring at for too long. I tried most online solutions but they just haven't worked very well...

I have a shell file. Let's called it "a". "a" looks a lot like this:


sh b.sh &
sh c.sh &

b.sh and c.sh look a lot like this:

run a process
run this opensource software over these files and wait
if condition; do
    sh e.sh

And then c.sh:

call some other programs
call some python files
call these shell files
... etc

Of course, f.sh and e.sh are similar and run their own processes and stuff.

Now, as you can see, when I run "a.sh", it runs a myriad of other things. I press Ctrl+C, and the processes are still running in the background. I close the terminal; same thing. I tried to kill with ID but I just don't know how to do it for a lot of the open source software I am using. Specifically, I have, for example tried this suggestion, but how do I make a.sh know the different processes being run in e.sh and so on so it can kill them? It hasn't been working I tell you.

Is there a command that lets me end all processes started by a shell file? I know this is so annoying but I cannot share the code as of right now. If you really need me to, I can post something that looks similar, but again, a lot of what I am doing is running software based on certain conditions and the software and shell files don't close when I hit Ctrl+C. So I am forced to pkill -U myuser, but this is impractical.


1 Answer 1


If pstree $(pgrep a) lists all the descendant processes of a you can send SIGTERM to all of them (includig a.sh) with:

kill $(pstree -p $(pgrep "a.sh") | awk -F"[)(]" '{for(i=2;i<=NF;i+=2)print $i}')

If that's not the case and neither kill -$(pgrep a) (notice the -) nor pkill -P $(pgrep a) can help I suggest you add a line to the beginning of the scripts and append its PID to a single file like this:

echo $$ >>/path/to/the/pidfile

This way you always have a list of PIDs available to kill with a simple:

kill </path/to/the/pidfile
  • Yeah, this was what I had to do. I wanted a more "bash" looking method, but unfortunately beggars cannot be choosers :(
    – John Lexus
    Dec 5, 2017 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.