Bash – Execute two commands and get exit status 1 if first fails

bashexit-status

In the case below, the report command must always be executed but I need to get an exit status 1 if the test command fails:

test;report
echo $?
0

How can I do it in a single bash line without creating a shell script?

Best Answer

Save and reuse $?.

test; ret=$?; report; exit $ret

If you have multiple test commands and you want to run them all, but keep track of whether one has failed, you can use bash's ERR trap.

failures=0
trap 'failures=$((failures+1))' ERR
test1
test2
if ((failures == 0)); then
  echo "Success"
else
  echo "$failures failures"
  exit 1
fi
Related Question