I run a Jenkins pipeline job with Groovy. The Groovy calls bash scripts for each step.
I want to fail the whole job when something in the way has errors.
For Groovy I use the returnStatus: true
.
For Bash I use set -e
.
But a bash script with set -e
, does not exit if, for example, a while
statement has errors. This is what should actually happen, according to the Linux manual page for 'set'.
I would like to know how to exit immediately in that scenario.
The script:
[jenkins-user@jenkins ~]$ cat script.sh
#!/bin/bash
set -xe
FILE=commands.txt
echo "echos before while"
# Run the commands in the commands file
while read COMMAND
do
$COMMAND
done < $FILE
echo $?
echo "echos after faulty while"
Let's say 'commands.txt' doesn't exist. Running script:
[jenkins-user@jenkins ~]$ sh script.sh
echos before while
script.sh: line 13: commands.txt: No such file or directory
1
echos after faulty while
[jenkins-user@jenkins ~]$ echo $?
0
Although the while
statement returns exit code 1, the script continues and ends successfully, as checked right after, with echo $?
.
This is how I force the Groovy to fail, after a step with bash/python/etc command/script returns a none-zero exit code:
pipeline {
agent any
stages {
stage("A") {
steps {
script {
def rc = sh(script: "sh A.sh", returnStatus: true)
if (rc != 0) {
error "Failed, exiting now..."
}
}
}
}
}
}
First question, how can I make the SHELL script to fail when the while/if/etc statements have errors? I know I can use command || exit 1
but it doesn't seem elegant if I have dozens of statements like this in the script.
Second question, is my Groovy error handling correct? Can anyone suggest an event better way? Or maybe there is a Jenkins plugin/official way to do so?