Bash-从子脚本退出父脚本

问题描述 投票:14回答:4

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

bash
4个回答
11
投票

尝试..

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

所以,

  • 当error_reporter将以退出状态> 0退出时,父代也会终止
  • 如果error_reporter将以状态= 0退出,则父级继续...

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


8
投票

尝试:

在父脚本中:

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

在子脚本中:

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

其他方式是:

在子脚本中:

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

但是,不建议这样做,因为父母需要掌握一些有关被杀死的信息,并在需要时进行一些清理。


另一种方法:而不是调用子脚本,请单击exec


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


0
投票

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

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

或更短

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

0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.