如果 bash "if statement"条件错误,则退出并出错



根据这篇文章:

if命令的退出状态应为已执行的thenelse复合列表的退出状态,如果未执行,则为零。

这导致我的bash脚本中出现一个错误,其中:

  • 我在脚本中设置了set -euo pipefail,并希望它在出现任何错误时停止执行
  • 我有一个if语句,它的条件是错误的,但执行仍在继续,因为-e不关心if语句中的条件

具体来说,我有一个if function1; then,我想屏蔽函数1不存在的情况。

场景是有人修改function1,它不再存在,但脚本运行良好,用户没有意识到脚本失败。

这是针对bash文件中的每个if语句的,所以这不是确保function1存在的问题,我正在为文件寻找一个一揽子解决方案,比如set -euo pipefail,它需要尽可能少的重构。

我看了整套文档,似乎没有什么合适的。

摘要:

功能1不存在

运行if function1; then ...

预期:

脚本退出

实际:

whatever.sh:line##:函数1:找不到命令

脚本继续

具体来说,我有一个if函数1;然后我想屏蔽函数1不存在的情况。

所以实现它。

fn_exists() { [[ "$(LC_ALL=C type -t -- "$1" 2>/dev/null)" = function ]]; }
call_fn_or_fail() {
if ! fn_exists "$1"; then
echo "hatever.sh: line ##: function1: command not found" >&2
exit 1
fi
"$@"
}
if call_fn_or_fail function1; then

我不明白你的问题。这是我为测试而写的一个脚本

#!/bin/bash
set -euo pipefail

somefunc(){
echo 'ok'
}

echo first if 
if somefunc; then 
echo yea it was there alright 
grep "gimme exit code 1" /etc/passwd
echo $?
fi
echo second if
#type somefunk
if somefunk; then
echo this should not happen
fi
echo end of script

如果在grep的退出代码1之后出现错误,则在我的/etc/passwd文件中找不到该字符串。

bash -x sotest.sh 
+ set -euo pipefail
+ echo first if
first if
+ somefunc
+ echo ok
ok
+ echo yea it was there alright
yea it was there alright
+ grep 'gimme exit code 1' /etc/passwd

这基本上正是你想要的。

评论grep,我们得到这个

./sotest.sh 
first if
ok
yea it was there alright
0
second if
./sotest.sh: line 20: somefunk: command not found
end of script

当然,第二个if失败了,脚本继续运行,这就是为什么你有一个if语句,你意识到了你得到错误的可能性,并且只运行"if";那么";如果这种情况没有发生。

你有两个选择。检查功能是否存在。不要用if调用它们。如果你试图调用一个不存在的函数,它会出错,脚本会退出。

我最终选择了一个bash脚本之外的解决方案。我输出这个bash脚本的结果,然后使用grep检查该输出是否有任何";命令未找到";行,如果是的话会出错。这并不是最初范围的一部分,而是我最终所做的。

相关内容

最新更新