bash - Shell/Bash : how to fail on just undefined functions in command-line shell?

标签 bash shell error-handling interrupt

我想确保我的命令行shell auto在未定义的函数上失败。

我不希望我的shell脚本在 undefined variable 上失败,因为那会弄乱我在.bashrc中采购的一些外部shell脚本(特别是.git-completion.bash开始带有set -u标志的行为异常)

我也不想在返回代码1上失败,因为那会使我的shell无法使用(如果获取文件中不存在的内容,则会自动退出我的shell)。

我想要的是随时停止使用未定义的函数。理想情况下,像kill -INT -$$这样的进程中断会立即停止当前进程并在那里退出,但不会退出 shell 程序,但是只要退出 shell 程序就行得通,只要它仅适用于未定义的函数,并且在捕获函数输出时也有效。

我的意思是捕获功能输出的工作只是设置set -uset -e甚至无法完全完成工作:

go1(){
  set -u
  set -e

  iDontExist

  echo "!!! reached operation after undefined !!!"
}
# > go1
# bash: iDontExist: command not found
# Saving session...bash: HISTTIMEFORMAT: unbound variable

以上作品。但是,如果我捕获输出,则这些标志不会捕获未定义的错误(即使由于问题开始时指定的原因,我什至不想使用这些标志)
go2(){
  set -u
  set -e
  set -o pipefail

  echo $(iDontExist)

  echo "!!! reached operation after undefined !!!"
}
# > go2
# bash: iDontExist: command not found
#
# !!! reached operation after undefined !!!

还有其他很棒的标志可以完成工作吗?

最佳答案

使用pipefailerrorexit时,您要使用以下方法清除错误状态:

may_fail_command || true

或在某种情况下处理退货状态

declare myvar
if ! myvar="$(may_fail_command)"; then
  printf 'Error assigning myvar because may_fail_command failed code %d\n' $?
fi

如果您必须在源文件中包含可能的错误,则可以暂时禁用errorexit nounset pipefail标志。

您还应该测试采购的退货代码

if ! source may_fail_sourced.sh; then
... handle sourcing errors
fi

关于bash - Shell/Bash : how to fail on just undefined functions in command-line shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57538232/

相关文章:

linux - 当我通过终端运行 shell 脚本时,它工作正常,当我在 jenkins 中运行时,它给出了错误

node.js - 在 docker 容器内安装 npm 时依赖项损坏

excel - 所有空白值的平均值错误处理

scala - Play Framework : How to implement proper error handling

Shell解析字符串

c# - ASP.NET MVC 中的异步错误 Controller

linux - 使用 awk 将变量替换为 ls 命令的结果

linux - Bash 脚本中 FTP 将文件复制到远程计算机失败

shell - hdfs 权限被拒绝

bash - shell脚本输出最大