7

There are a few commands in a script I need to run, it's a custom linter for source code. Each run generates a report and fails with exit code 1 in case of rules violations. I need to run all commands to generate reports before failure, and fail if any command fails with non-zero exit code. This script doesn't work because it exists on first error:

lint ./module1/src/main/java && lint ./module2/src/main/java && lint module3/src/main/java

Now I'm using this script:

lint ./module1/src/main/java
code1="$?"
lint ./module2/src/main/java
code2="$?"
lint ./module3/src/main/java
code3="$?"

if [[ "$code1" != "0" || "$code2" != "0" || "$code3" != "0" ]]; then
  exit 1
fi

But it looks overcomplicated and it's not extendable (I need to add additional variables and check for next command).

Is it possible to make this script more elegant?

0

2 Answers 2

14

If you want all your tests to complete, and then return a final overall status code, that's how you have to code it. Here's one way

#!/bin/bash
#
ss=0

lint ./module1/src/main/java || ((ss++))
lint ./module2/src/main/java || ((ss++))
lint ./module3/src/main/java || ((ss++))

exit $ss

As written it fails with an exit code corresponding to the number of failed tests. You can still test for true/false (zero/non-zero), but if you require the code to exit with precisely 1 in the event that any one or more tests have failed, change ((ss++)) to ss=1 throughout.

0
2

It's a bit of a hack, but you can use xargs for this purpose. By default it runs all commands, and exits with status 123 if any of them failed.

Here, we run three commands, all of which fail, but all are executed:

echo '
echo 1 && exit 1
echo 2 && exit 1
echo 3 && exit 1
' | xargs -d "\n" -L1 -I{} bash -c {}

That exits with exit status 123 (GNU xargs), but outputs the following, showing that all three commands were run:

1
2
3

A similar set of commands that all succeed exit with status 0:

echo '
echo 1 && exit 0
echo 2 && exit 0
echo 3 && exit 0
' | xargs -L1 -I{} bash -c {}

Here the exit status is 0, as you'd expect.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .