简体   繁体   English

运行多个 bash 命令,如果其中之一在 bash 中失败,则返回 false

[英]Run Multiple bash commands and return false if one of them fails in bash

I am setting up a script that will execute a series of bundle exec rspec commands and I want it to return false if any of them fail.我正在设置一个脚本,该脚本将执行一系列 bundle exec rspec 命令,如果其中任何一个失败,我希望它返回 false。 But I still want it to run all the tests.但我仍然希望它运行所有测试。 Is there a shorter way to accomplish this without a bunch of if or test statements?没有一堆 if 或 test 语句,有没有更短的方法来完成这个?

I'm doing it currently like this, but I'll update the answer with nicer syntax if I'm able to write a bash function to handle this:我目前正在这样做,但如果我能够编写一个 bash 函数来处理这个问题,我会用更好的语法更新答案:

#!/bin/sh
set +x

RETVAL=0

command1 || RETVAL=1
command2 || RETVAL=1
command3 || RETVAL=1

exit $RETVAL

Track their exit code in a variable, and exit with it.在变量中跟踪他们的退出代码,然后退出。 I added the line number to for troubleshooting what broke.我添加了行号以排除故障。

declare -i r_code=0    # return code
command1 || { r_code+=$?; echo "ERROR at $LINENO
}

command2 || { r_code+=$?; echo "ERROR at $LINENO
}

exit $r_code

This is a for loop that will go through all the return codes and if one failed will exit with the first seen failed return code.这是一个 for 循环,它将遍历所有返回代码,如果一个失败,将退出第一个看到的失败返回代码。

i=0
rc=0
command1 
rcode[i]=$?
i=i+1
command2
rcode[i]=$? ... n
for i in "${rcode}"
do
   if [ $i -ne 0 ]; then
      rc=$i
      break
   fi
done
exit $rc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM