从命令替换中退出脚本时出错

Wil*_*ard 6 bash error-handling command-substitution

如果我有一个函数:

myfunction() {
  [ -d somedirectory ] && [ "some other condition" ] || { echo "error" >&2 ; exit 1; }
  global_var=somevalue
}
Run Code Online (Sandbox Code Playgroud)

我从另一个函数中调用它:

some_other_function() {
  myfunction
  # Do something with "$global_var"
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作:如果条件myfunction失败,错误退出将终止整个脚本以防止执行其他代码。

在重构与其他脚本(在源文件中)共享函数定义的非常大的脚本时,我想通过返回一些全局变量来删除它们,如下所示:

myfunction() {
  [ -d somedirectory ] && [ "some other condition" ] || { echo "error" >&2 ; exit 1; }
  local somevar=somevalue
  # do stuff with "$somevar", then...
  # return value of somevar to calling function.
  printf %s "$somevar"
}

some_other_function() {
  local anothervar="$(myfunction)"
  # Do something with "$another_var"
}
Run Code Online (Sandbox Code Playgroud)

但是,此处的错误退出未能按预期工作。它不会杀死脚本,而只会杀死该函数,该函数由于命令替换而在子 shell 中执行。

有没有一种方法可以模块化这个大型脚本,以允许从函数返回文本值(而不是使用全局变量),并且仍然允许函数从整个脚本中错误退出?

Hau*_*ing 3

您必须向主 shell 发送信号:

# start of the main script:
MAIN_SHELL_PID=$$

[...]

myfunction() {
    ... || { echo "error" >&2 ; kill -HUP "$MAIN_SHELL_PID"; }
}
Run Code Online (Sandbox Code Playgroud)

  • 您不需要变量“MAIN_SHELL_PID”。使用“$$”也同样有效。 (2认同)