How to get curl exit status from sh step command?

Viewed 2457

I'm trying to get the result of a command into a boolean variable in my Jenkinsfile. The command is: curl -o/dev/null -sfI "$url", which can be used in sh like this:

if ( curl -o/dev/null -sfI "$url" ); then
  echo "URL exists"
else
  echo "URL does not exist"
fi

So, I need this condition in my jenkinsfile but I don't know how to recreate it. This is what I've tried:

def fileAlreadyExists = sh(
                script: "curl -o/dev/null -sfI \"$url\"",
                returnStdout: true
        )

But seems to return false always.

1 Answers

Your command does not return any output due to -o /dev/null switch. If you want to catch exit code you would have to set returnStatus and not returnStdout option, like:

def fileAlreadyExists = sh(
            script: "curl -o/dev/null -sfI \"$url\"",
            returnStatus: true
)

Alternatively you could extend your Bash command to do echo $? after the curl command to echo last command exit code:

def fileAlreadyExists = sh(
            script: "curl -o/dev/null -sfI \"$url\"; echo \\\$?",
            returnStdout: true
) as Integer // explicit casting needed, because it returns String

The variable fileAlreadyExists stores an integer value, so you can use it in if () statement (Groovy evalutes if (0) to false, so if you expect 0 exit code then it is good idea to make this comparison explicit like:

if (fileAlreadyExists == 0) { /* exists */ } else { /* not exist */ }

As a side note: remember to escape \ if you want to pass it to the sh command - Jenkins strips single escape character, so if you want to pass e.g. double quote the underlying script then you have to escape it in the following way: \\\".

Related