Bash - 从子脚本退出父脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16215196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:16:31  来源:igfitidea点击:

Bash - Exit parent script from child script

bash

提问by user1049697

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 exitfrom 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?

我有一个 Bash 父脚本,它在意外输入时调用记录错误的错误记录子脚本。我还希望在发生错误并调用错误脚本时停止执行。但是如果我exit从错误处理脚本调用它不会停止父脚本的执行。我该如何停止孩子的父脚本?

采纳答案by jm666

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...
  • 当 error_reporter 以退出状态> 0 退出时,父级也将终止
  • 如果 error_reporter 将以 status = 0 退出,则父级继续...

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 stopand he will stop itself (if want) ;)

你不想要stop the parent from a child父母通常不喜欢这种行为):),你想要tell to parent - need stop,他会停止自己(如果想要);)

回答by anishsane

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, execit.

另一种方式:而不是调用子脚本,exec它。



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

但是,正如其他答案中所指出的,最干净的方法是在孩子返回后从父母退出。

回答by valosekj

Extension to @anishsane comment because MacOS has little bit different pssyntax.

对@anishsane 注释的扩展,因为 MacOS 的ps语法略有不同。

Finding parent process ID (ppid) in child script under Mac OS (Darwin):

在 Mac OS (Darwin) 下的子脚本中查找父进程 ID (ppid):

kill -SIGUSR1 $(ps $$ -o ppid=);exit

kill -SIGUSR1 $(ps $$ -o ppid=);exit

回答by Ansgar Wiechers

Don't try to terminate the parent from the child. Instead call exitin the parent after the child script returned.

不要试图从孩子中终止父级。而是exit在子脚本返回后调用父脚本。

if [ condition ]; then
  /path/to/child.sh
  exit 1
fi

or shorter

或更短

[ condition ] && { /path/to/child.sh; exit 1; }