Squidly
Squidly

Reputation: 2717

Aggregate failure codes in bash

I've got a script which has multiple stages, and at each stage it's possible to fail, but the script can carry on running.

Concretely, I generate some json, and check if the diff is correct. The diff could be wrong, but it doesn't stop the next stage of json being produced.

How can I aggregate the failure codes of diff, so that I return 1 if any diff returned > 1, and zero otherwise, without just ending as soon as a failure occured?

Basically, it's just folding || over the result codes, but I can't seem to find a nice way to || a string with a return code.

Skeleton:

main_result=0
for s in stage1 stage2 stage3; do
    diff <(generate-stuff) expected-$stage
    result=$?
    # something like main_result=$main_result || $result
done

exit $main_result

Upvotes: 1

Views: 86

Answers (2)

rr-
rr-

Reputation: 14811

What you're looking for is $(()) which is explained here:

#!/bin/sh
main_result=0
main_result=$((main_result || 0))
echo $main_result
main_result=$((main_result || 1))
main_result=$((main_result || 0))
echo $main_result

Results in:

0
1

So all you need to do is

main_result=$((main_result || $?))

Upvotes: 2

P.P
P.P

Reputation: 121387

Logical or can be done as:

main_result=$((main_result || result))

Upvotes: 2

Related Questions