我想确保我的命令行shell auto在未定义的函数上失败。
我不希望我的shell脚本在 undefined variable 上失败,因为那会弄乱我在.bashrc中采购的一些外部shell脚本(特别是.git-completion.bash开始带有set -u
标志的行为异常)
我也不想在返回代码1上失败,因为那会使我的shell无法使用(如果获取文件中不存在的内容,则会自动退出我的shell)。
我想要的是随时停止使用未定义的函数。理想情况下,像kill -INT -$$
这样的进程中断会立即停止当前进程并在那里退出,但不会退出 shell 程序,但是只要退出 shell 程序就行得通,只要它仅适用于未定义的函数,并且在捕获函数输出时也有效。
我的意思是捕获功能输出的工作只是设置set -u
,set -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 !!!
还有其他很棒的标志可以完成工作吗?
最佳答案
使用pipefail
和errorexit
时,您要使用以下方法清除错误状态:
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/