Bash `if` 语句与条件执行逻辑

问题描述 投票:0回答:1

这有效,因为它应该

$ bash -cx 'echo $BASH_VERSION; set -euo pipefail; if true; then (echo good reaction, bad result >&2; exit 1); else echo bad reaction; fi'
+ echo '5.2.21(2)-release'
5.2.21(2)-release
+ set -euo pipefail
+ true
+ echo good reaction, bad result
good reaction, bad result
+ exit 1

但是使用条件语句的类似片段则不然。我明白为什么它不会(虽然我不确定为什么 errfail 设置不会停止执行),但想知道是否有一种方法可以使条件执行像

if
语句那样工作

$ bash -cx 'echo $BASH_VERSION; set -euo pipefail; true && ( (echo good reaction, bad result >&2; exit 1); ) || { echo bad reaction; }'
+ echo '5.2.21(2)-release'
5.2.21(2)-release
+ set -euo pipefail
+ true
+ echo good reaction, bad result
good reaction, bad result
+ exit 1
+ echo bad reaction
bad reaction
bash if-statement conditional-statements logic
1个回答
0
投票

假设您要接受建议而不使用

set -euo pipefail
那么我认为问题实际上只是如何使用条件来模仿:

if command1; then command2; else command3; fi

所以那就是:

command1 && { command2; true } || { command3; }
© www.soinside.com 2019 - 2024. All rights reserved.