Mahbub Rahman Mahbub Rahman - 4 years ago 306
Bash Question

SHELL: Build step 'Execute shell' marked build as failure

I have the following script as a post build step in Jenkins:

#!/bin/sh
out=$(sudo curl http://192.168.33.19:8080/job/$JOB_NAME/lastBuild/api/json/json.tail.test --user "jenkins:jenkins" | jq -r '.result')

res=$(echo $out|grep "FAIL")

if [ "$res" = "FAILURE" ]; then
curl -X POST -d 'json={"RESULT":"'$res'","JOB_NAME":"'$JOB_NAME'","BUILD_NUMBER":"'$BUILD_NUMBER'"}' http://localhost:8888/jenkins.e2e.build.status
fi;


The build is SUCCESS but after executing the script, result becomes FAILURE with below console output in Jenkins:

+ out=SUCCESS
++ grep FAIL
++ echo SUCCESS
+ res=
Build step 'Execute shell' marked build as failure
Xvfb stopping
Finished: FAILURE


What is the mistake I made in the script?

Answer Source

Your input lines,

res=$(echo $out|grep "FAIL")
if [ "$res" = "FAILURE" ]; then

don't make much sense as you are trying to search for the string FAIL on a string SUCCESS, the res variable would obviously be empty,

echo "SUCCESS" |grep  "FAIL"
                                  #  Empty output returned
echo $?
1                                 #  Code '1' indicating failure error code of grep

in cases of string comparison like these, you need the exit code of the grep to determine a search success/failure.

Just use the exit code of grep directly and ask it run silently using the -q flag. The below conditional executes the cURL request when it finds the FAIL string from the earlier string output.

if grep -q "FAIL" <<<"$out" 
then
    curl -X POST -d 'json={"RESULT":"'$res'","JOB_NAME":"'$JOB_NAME'","BUILD_NUMBER":"'$BUILD_NUMBER'"}' http://localhost:8888/jenkins.e2e.build.status
fi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download