在 bash 中对退出代码进行 AND 运算

2024-04-07

我有一个 bash 脚本,它对我的​​源代码运行三项检查,然后exit 0如果所有命令都成功,或者exit 1如果其中任何一个失败:

#!/bin/bash

test1 ./src/ --test-1=option
exit_1=$?

test2 ./src/ test-2-options
exit_2=$?

test3 ./src/ -t 3 -o options
exit_3=$?

# Exit with error if any of the above failed
[[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]]
exit $?

这段代码可以工作,但感觉过于冗长和冗长。有什么方法可以让它变得更好吗?具体来说,我不满意的是:

  • 必须运行命令,并且then将退出代码分配给变量
  • 不得不使用[[ ... ]], then在下一行收集其退出代码以退出
  • 必须显式地将变量与 0 进行比较,如下所示[[ $var -eq 0 ]],而不是将它们视为布尔值

理想情况下,最终结果将更具可读性,例如:

exit_1=( test1 ./src/ --test-1=option )
exit_2=( test2 ./src/ test-2-options )
exit_3=( test3 ./src/ -t 3 -o options )

# Exit with error if any of the above failed
exit ( $exit_1 && $exit_2 && $exit_3 )

我考虑过的一些事情:


在一行中将错误代码输入到变量中:

exit_1=$( test1 ./src/ --test-1=option )$?
exit_2=$( test2 ./src/ test-2-options )$?
exit_3=$( test3 ./src/ -t 3 -o options )$?

这很有效,并且使时间变得更短,但我以前从未见过其他人使用过它。这是明智/理智的做法吗?这有什么问题吗?


只需运行测试,然后 && 将它们放在一起:

test1 ./src/ --test-1=option && \
test2 ./src/ test-2-options && \
test3 ./src/ -t 3 -o options
status=$?

这确实not工作,如 bash 短路。如果test1失败,测试 2 和测试 3 不运行,我希望它们全部运行。


检测错误并退出使用|| exit

[[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] || exit 1

这节省了一行尴尬的退出代码和变量,但重要的是exit 1现在就在队伍的末端,您可能会错过它。理想情况下,这样的事情会起作用:

exit [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]]

当然,这确实not工作,作为[[返回其输出而不是回显它。

exit $( [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] ; echo $? )

does工作,但看起来仍然是一个可怕的障碍


没有明确处理退出代码作为布尔值

[[ $exit_1 && $exit_2 && $exit_3 ]]

这并没有达到您希望的效果。将 && 一起存储在变量中的三个返回码的最简单方法是使用完整的$var -eq 0 && ...。当然有更好的方法吗?


我知道 bash 不是一种很好的编程语言 - 如果你甚至可以这样称呼它 - 但有什么办法可以让这不那么尴尬吗?


您可以使用bash的算术命令OR将退出代码放在一起,并对结果求反,如果任何代码非零,则获得退出代码 1。首先,举个例子:

$ ! (( 0 | 0 | 0 )); echo $?
0
$ ! (( 1 | 0 | 0 )); echo $?
1

现在,你的脚本:

#!/bin/bash

test1 ./src/ --test-1=option; exit_1=$?
test2 ./src/ test-2-options;  exit_2=$?   
test3 ./src/ -t 3 -o options; exit_3=$?

# Exit with error if any of the above failed. No need for a final
# call to exit, if this is the last command in the script
! (( $exit_1 || $exit_2 || $exit_3 ))

或者一般来说,您可以在运行任意数量的测试时累积退出代码:

#!/bin/bash

# Unfortunately, ||= is not an assignment operator in bash.
# You could use |=, I suppose; you may not be able to assign
# any meaning to any particular non-zero value, though.
test1 ./src/ --test-1=option; (( exit_status = exit_status || $? ))
test2 ./src/ test-2-options;  (( exit_status = exit_status || $? ))  
test3 ./src/ -t 3 -o options; (( exit_status = exit_status || $? ))
# ...
testn ./src "${final_option_list[@]}"; (( exit_status = exit_status || $? ))

exit $exit_status   # 0 if they all succeeded, 1 if any failed
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 bash 中对退出代码进行 AND 运算 的相关文章

随机推荐