grep -v 'Time elapsed' exits with status code 1 only if every input line did not contain Time elapsed, but this will never happen as mvn seems to always print a summary.
According to this website, the output of mvn clean test looks as follows if there are tests
-------------------------------------------------------
T E S T S
-------------------------------------------------------
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.547 sec
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
and according to this question, as follows if there are no tests
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
In both cases, grep 'Tests run:' will print at least the summary in the last line. The summary never contains Time elapsed. Therefore grep -v 'Time elapsed' always exits with status code 0.
Try the following script instead:
#!/bin/bash
if ! mvn clean test | grep -q '^Tests run: [^0]'; then
echo "No Unit tests to run!";
fi
For the outputs shown in this question, we could use if mvn clean test | grep -Fxq 'There are no tests to run.' instead. But I found other sample outputs where mvn did not print that string; sometimes even no summary. The first script handles all of these cases too.