Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Exit parent script from child script

Tags:

bash

I have a Bash parent script that on unexpected input calls an error logging child script that logs the error. I also want the execution to halt when the error occurs and the error script is called. But if I call exit from the error handling script it does not stop the parent script from executing. How may I go about stopping a parent script from a child?

like image 571
user1049697 Avatar asked Apr 25 '13 12:04

user1049697


2 Answers

try..

#normal flow
[[ $(check_error_condition) ]] && /some/error_reporter.sh || exit 1

so,

  • when the error_reporter will exit with exit status > 0 the parent will terminate too
  • if the error_reporter will exit with status = 0 the parent continues...

You don't want stop the parent from a child (the parents usually don't like this behavior) :), you instead want tell to parent - need stop and he will stop itself (if want) ;)

like image 154
jm666 Avatar answered Sep 18 '22 12:09

jm666


Try:

In parent script:

trap "echo exitting because my child killed me.>&2;exit" SIGUSR1

In child script:

kill -SIGUSR1 `ps --pid $$ -oppid=`; exit

Other way was:

In child script:

kill -9 `ps --pid $$ -oppid=`; exit

But, it is not recommended, because the parent needs to have some information about getting killed & thus do some cleanup if required.


Another way: Instead of calling the child script, exec it.


However, as pointed out in other answer, the cleanest way is to exit from parent, after the child returns.

like image 28
anishsane Avatar answered Sep 20 '22 12:09

anishsane