简体   繁体   中英

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. 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?

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:

#!/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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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