When I run an Execute shell
build step to execute a script and that script returns 0
, Jenkins
flags the build as SUCCESS
, otherwise it flags it as FAILURE
which is the expected default behaviour as 0
means no errors and any other value represents an error.
Is there a way to mark a build as SUCCESS
only if the return value matches a specific value other than 0
(e.g. 1
,2
,3
...)?
PS: in case you're wondering why I'm looking for that, this will allow me to perform unit testing of Jenkins itself as my scripts are written to return different exit values depending on various factors, thus allowing me to expect certain values depending on certain setup mistakes and making sure my whole Jenkins integration picks up on those.
- $EXPECTED_EXIT_CODE is one of my job parameters which defines the exit code I'm expecting. -The if statement simply does the following: if I get the expected exit code, exit with 0 so that the build is marked as SUCCESS , else exit with 1 so that the build is marked as FAILURE .
The exit code (also called "exit status") is an integer from 0 to 255. The batch system reports this exit code.
/path/to/myscript.sh || if [ "$?" == "$EXPECTED_EXIT_CODE" ]; then continue; else exit 1; fi
I would use continue instead of exit 0 in case you have other items below that you need to run through.
Alright, I went on IRC #jenkins
and no-one new about a plugin to set a particular job status depending on a particular exit code :( I managed to do what I wanted by creating an Execute shell
step with the following content:
bash -c "/path/to/myscript.sh; if [ "\$?" == "$EXPECTED_EXIT_CODE" ]; then exit 0; else exit 1; fi"
-Running the script under bash -c
allows catching the exit code and prevents Jenkins
from stopping build execution when that exit code is different than 0 (which it normally does).
-\$?
is interpreted as $?
after the script execution and represents its exit code.
-$EXPECTED_EXIT_CODE
is one of my job parameters which defines the exit code I'm expecting.
-The if
statement simply does the following: if I get the expected exit code, exit with 0 so that the build is marked as SUCCESS
, else exit with 1 so that the build is marked as FAILURE
.
Can handle it via the Text-finder Plugin:
Failed on XXX - Exiting with RC 2
Exiting with RC [2-4]
.I do it like this:
set +e
./myscript.sh
rc="$?"
set -e
if [ "$rc" == "$EXPECTED_CODE_1" ]; then
#...actions 1 (if required)
exit 0
elif [ "$rc" == "$EXPECTED_CODE_2" ]; then
#...actions 2 (if required)
exit 0
else
#...actions else (if required)
exit "$rc"
fi
echo "End of script" #Should never happen, just to indicate there's nothing further
Here +e
is to avoid default Jenkins behavior to report FAILURE on any sneeze during your script execution. Then get back with -e
.
So that you can handle your exit code as appropriate, else eventually FAIL with the returned code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With