Filter output and receive exit code simultaneously with the program in the Linux shell

I work in Jenkins (Jenkins is an open source continuous integration tool), running a list of shell commands. One of the commands is to run a Java program that does some data validation. If it encounters an invalid date, the Java program will exit with a zero exit code so that Jenkins can detect that this time the assembly failed.

Unfortunately, the Java program prints too much log in stdout and stderr, only some of them are useful. Since the Java program cannot be changed, I decide to filter the output using grep. So I wrote a shell like:

java -cp $CLASSPATH MetaValidatorMain | grep -v "useless keyword1"| grep -v "useless keyword2"

But the problem is that after the shell line was executed, the parent process (Jenkins) received the grep indead java exit code, so Jenkins could not determine if the build was successful.

I also tried this:

(java -cp $CLASSPATH MetaValidatorMain || exit 1) | grep -v "useless keyword1"| grep -v "useless keyword2"

doesn't work either.

Can someone tell me how I can write a shell line to filter the output and get the correct exit code at the same time.

THX

+3
source share
2 answers

There are three ways to do this. However, your current setup should work. The reason is that grep will not match anything if the command fails, so grep will return with a status 1(if the program does not always show this text no matter what).

Pipefail

- pipefail. , , , $? ( , ).

# false | true; echo $?
0
# set -o pipefail
# false | true; echo $?
1

$PIPESTATUS

Bash $PIPESTATUS, .

# true | true; echo "${PIPESTATUS[@]}"
0 0
# false | true; echo "${PIPESTATUS[@]}"
1 0
# false | true; echo "${PIPESTATUS[0]}"
1
# true | false; echo "${PIPESTATUS[@]}"
0 1

, , .

. , $PIPESTATUS bash, .

.

# java -cp $CLASSPATH MetaValidatorMain > /tmp/outfile.txt 2>&1
# RETURN_CODE=$?
# grep -v "useless keyword1" /tmp/outfile | grep -v "useless keyword2"
# exit RETURN_CODE
+1

, , grep :

java -cp $CLASSPATH MetaValidatorMain > /tmp/outfile.txt 2>&1
RETURN_CODE=$?
grep -v "useless keyword1" /tmp/outfile | grep -v "useless keyword2"
exit RETURN_CODE
+2

All Articles