首页 > 解决方案 > 与我的本地结果相比,为什么 Jenkins shell 脚本给出的结果与同一命令不同?

问题描述

我正在尝试在变量中捕获 http 请求的响应。以下问题为我提供了完美的解决方案(如何评估来自 bash/shell 脚本的 http 响应代码?)。当我在本地执行此命令时

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

它给了我想要的 http 代码(例如 400)。然而在詹金斯我执行相同的命令,但它给了我一个空的响应:

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
                            
'''

标签: bashjenkinsjenkins-pipeline

解决方案


您正在将 groovy syntex 与 bash 混合,它必须如下所示

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
        """
    }
}

和输出将是

在此处输入图像描述


推荐阅读