0

I am trying to capture the response of an http request in a variable. The following question gave me the perfect solution to this (How to evaluate http response codes from bash/shell script?). When I execute this command locally

response=$(curl --write-out '%{http_code}' --silent --output /dev/null http://localhost:8082/url)
echo $response

It gives me the wanted http code (e.g. 400). However in Jenkins I execute the same command, but it gives me an empty response:

sh '''#!/bin/bash
      DOCKER_RESPONSE=$(curl --write-out '%{http_code}' --silent --output /dev/null http://localhost:8002/route?json={})
      while [[ $DOCKER_RESPONSE != 200 ]]
      do
        sleep 1
        echo "$DOCKER_RESPONSE"
        DOCKER_RESPONSE=$(curl --write-out '%{http_code}' --silent --output /dev/null http://localhost:8002/route?json={})
      done
                            
'''
Tibo Geysen
  • 177
  • 2
  • 11
  • If you want to have the output of `sh` command, you have to use `def shell_output = sh returnStdout: true, script: ``` ... ``` `. Otherwise it's possible that `"200" != 200` as one is string and another is number. – MaratC Feb 23 '21 at 20:00

1 Answers1

0

you are mixing groovy syntex with bash , it has to be like below

node {
    stage('one') {
        sh """
          res=\$(curl --write-out '%{http_code}' --silent --output /dev/null https://google.com)
          echo \$res
          while [[ \$res != '301' ]]
          do
            sleep 1
            echo \$res
            res=\$(curl --write-out '%{http_code}' --silent --output /dev/null https://google.com)
          done
        """
    }
}

and The output will be

enter image description here

Samit Kumar Patel
  • 1,932
  • 1
  • 13
  • 20
  • The OP used a non-expanding syntax with three single quotes and so they have no need to escape the `$` character. – MaratC Feb 23 '21 at 20:01