4

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?

14

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
9

What is a shell script except a file containing shell commands? You could pretend it's not a shell script and put it on one line with something like:

(test; r=$?; report; [ "$r" -gt 0 ] && exit 1; exit 0)

This exits the subshell with a 1 if the first command returned anything other than 0; otherwise, it returns 0.

For examples -- I'm just echoing something in lieu of running a real program:

$ (false; r=$?; echo report; [ "$r" -gt 0 ] && exit 1; exit 0)
report
$ echo $?
1
$ (true; r=$?; echo report; [ "$r" -gt 0 ] && exit 1; exit 0)
report
$ echo $?
0
$ # example with an exit-status of 2:
$ (grep foo bar; r=$?; echo report; [ "$r" -gt 0 ] && exit 1; exit 0)
grep: bar: No such file or directory
report
$ echo $?
1

If you regularly set the errexit shell option, you'd want to add in an override so that the subshell doesn't exit prematurely:

(set +o errexit; false; r=$?; echo report; [ "$r" -gt 0 ] && exit 1; exit 0)
4

You said "exit status 1 if the test command fails". Assuming you intended to make that distinction (i.e., you want the exit value to be 1 even if the test command exits with, say, 2, or 3, or whatever), then this is a decent solution:

test && { report; true; } || { report; false; }

If you did not really mean "1", but whatever non-zero that test exited with would be OK as your overall exit code, then the current top answer (save and reuse $?) works fine.

0

A really bad idea, but this seems to work, for some inspiration:

(trap report exit; test)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.