如何从源bash脚本返回错误 [英] How to return the error from a sourced bash script

查看:43
本文介绍了如何从源bash脚本返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash脚本还很陌生.我有4个嵌套的bash脚本,并且在适当地传播第4个脚本中的错误时遇到了麻烦.例如:

I'm fairly new to bash scripting. I have 4 nested bash scripts, and i'm having trouble propogating the error from the 4th script appropriately. eg:

script1.sh:
  source script2.sh
  <check for error and display appropriate message>
script2.sh:
  source script3.sh param_1
  <return to script1 on error>
  source script3.sh param_2
  <return to script1 on error>
  source script3.sh param_n
  <return to script1 on error>
script3.sh
  <some processing>
  script4.sh
  echo "this statement is not reached"
  return $?
script4.sh
  <some processing>
  exit $?

我的要求是:

  1. 我需要在script1中定义一个关联数组,该数组在script2中填充,并在script3的范围内可用.我认为唯一的方法就是源script2和script3
  2. script4的执行不是源代码,因为此脚本也可以独立于这些父脚本执行

线程讨论了使用return从源bash脚本返回的语句,但是当执行script4时,我需要退出.我不明白为什么script4中的exit语句会导致原始外壳程序和子外壳程序都终止?当然应该只退出子外壳吗?

This thread talked about using the return statement to return from a sourced bash script, but as script4 is executed i need to exit. I don't understand why the exit statement in script4 causes both the original shell and the sub shell to terminate? Surely it should only exit the sub shell?

我需要查看信号和陷阱吗?

Do i need to look at signals and traps?

感谢您的帮助

推荐答案

如果需要,可以保持 set -e 启用.然后,在调用已知退出状态可能为非零的脚本时,您将需要格外小心:

You can keep set -e enabled if you want. Then you'll have to be more careful about invoking a script where you know the exit status may be non-zero:

script3.sh
  <some processing>
  if script4.sh; then
    rc=0
  else
    rc=$?
  fi
  echo "script4 complete"
  return $rc

请参见 https://www.gnu.org/software/bash/manual/bashref.html#index-set

IMO,使用 set -e 是合适的.在这里,您要<检查错误并显示适当的消息> ,显然不是这种情况.

IMO, using set -e is appropriate if you truly want to abort your program for any error. Here, where you want to <check for error and display appropriate message>, that's clearly not the case.

这篇关于如何从源bash脚本返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆