19

Probably a simple question but an elegant solution is not coming to mind. I would like to run a series of commands (each one is a test) and return 1 if any of them returned non-zero. Typically I would do something like:

thingA && thingB && thingC
exit $?

However, that won't run thingC if thingB fails and I want to ensure that all 3 run. I can easily think of an inelegant approach:

final_result=0
retval=thingA
if [[ $retval != 0 ]] then
  final_result=1
fi
retval=thingB
...
exit $final_result

Is there some simple, elegant way to get what I want?

Pace
  • 38,293
  • 12
  • 111
  • 142

1 Answers1

20

Is this elegant enough?

status=0
thingA || status=1
thingB || status=1
thingC || status=1
exit $status

You can use $? instead of 1 if you prefer. Or you could identify the last command that failed by using statuses 1, 2, 3 when you do the assignment. If you wanted to know the first command that failed, you'd have to test $status before assigning to it.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229