bash - 运行多个命令,如果其中一个命令失败则让脚本失败

标签 bash

我想创建一个 bash 脚本,在特定的代码库上运行各种测试(单元、集成、API 测试等)。我想强制此脚本在每个构建上运行所有测试,并且只有在至少一个测试运行失败时才让构建失败。

我有一个可行的解决方案,但我感觉很糟糕。如果有人有想法来改进这一点,我将不胜感激。

#!/usr/bin/env bash

set -e 

#...
#some other code which should let the build fail immediately if something is wrong

set +e
runUnitTests.sh
unitTestsFailed=$?

runIntegrationTests.sh
integrationTestsFailed=$?

runApiTests.sh
apiTestsFailed=$?

if [ $unitTestsFailed -ne 0 ] || \
   [ $integrationTestsFailed -ne 0 ] || \
   [ $apiTestsFailed -ne 0 ]; then

    echo "Automated tests failed"
    exit 1
else
    echo "Automated tests succeeded"
    exit 0
fi

最佳答案

您可以使用通用函数运行每个测试脚本,该函数检查失败并设置错误标志。

failure=0

testSuite() {
    "$@" || failure=1
}
testSuite runUnitTests.sh
testSuite runIntegrationTests.sh
testSuite runApiTests.sh
if ((failure)); then
    echo "Automated tests failed" >&2
    exit 1
else
    echo "Automated tests succeeded" >&2
    exit 0
fi

关于bash - 运行多个命令,如果其中一个命令失败则让脚本失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195315/

相关文章:

regex - Grep 正则表达式 : How to find multiple area codes in phone number?

linux - 如何删除两种模式之间的 block 文本?

android - ansible android更新sdk给找不到sdkmanager.jar

linux - 在 Bash 编程中从标准输入读取

macos - 自动水印 - 文件夹操作

mysql - bash用户输入Mysql登录

java如何调用外部unix命令

linux - 在许多文件中用多行替换字符串

linux - 等待第二个脚本触发直到第二个脚本的所有后台并行进程完成?

bash - 如何在 Perl 中使用 Shell 参数扩展?