【问题标题】:Why is Jenkins shell scripting giving other results than for the same command compared to my local results?与我的本地结果相比,为什么 Jenkins shell 脚本给出的结果与同一命令不同?
【发布时间】:2021-05-25 18:55:50
【问题描述】:

我正在尝试在变量中捕获 http 请求的响应。以下问题为我提供了完美的解决方案(How to evaluate http response codes from bash/shell script?)。当我在本地执行此命令时

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

【问题讨论】:

  • 如果你想得到sh命令的输出,你必须使用def shell_output = sh returnStdout: true, script: ``` ... ``` 。否则"200" != 200 可能一个是字符串,另一个是数字。

标签: bash jenkins jenkins-pipeline


【解决方案1】:

您正在将 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
        """
    }
}

输出将是

【讨论】:

  • OP 使用了带有三个单引号的非扩展语法,因此他们无需转义 $ 字符。
猜你喜欢
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多