Home > Software engineering >  Pass value that contains double quotes as batch file parameter in Jenkins
Pass value that contains double quotes as batch file parameter in Jenkins

Time:10-15

I am working with a simple Jenkins script that obtains a result from a curl GET request, stores it in a variable, and then sends that value to a batch file as a parameter

    stage('test-stage') {
        steps {
          script {
              final String response = bat(script:'curl -X "GET" "www.someworkingurl.com" -H "accept: application/json"', returnStdout: true).trim()
              echo response
              bat """ "C:\\somepathto\\mybatchfile.cmd" "${response}" """
          }
        }
    }

Although the echo shows the expected response (body returned from the server), immediately after it fails to pass correctly to the batch file. If I understand correctly, because the response contains text with double quotes as well ( such as a json file ) it might be breaking the ability for that line to pass the value correctly, and causes it to break apart as if each word that is in between quotes in the response is being interpreted as a command.

I have been unable to find a way around this, nor can I find a solution online. Searches for such generic terms (jenkins escape double quote in string) lead to results that show how to manually escape double quotes in static strings in the jenkins pipelines, which is not what I am trying to achieve.

How can I get this to work correctly?

CodePudding user response:

Have you try this with ecaped quotes:

bat """ \"C:\\somepathto\\mybatchfile.cmd\" \"${response}\" """

you can also try this:

env.response = response
bat ''' "C:\\somepathto\\mybatchfile.cmd" "${response}" '''

With "env." this is an environment variable and can be accessed in the batch.

CodePudding user response:

Another option to try, which will add escape characters in your response

def newRes = response.replaceAll('"', '\\\\"')
bat """ "C:\\somepathto\\mybatchfile.cmd" ${newRes} """
  • Related