Shell 脚本中的 Jenkins Pipeline 环境变量创建一个新行

Joh*_*een 0 bash shell jenkins jenkins-pipeline

我正在尝试访问 Jenkins 管道中的 env 变量,并希望在同一管道中执行但步骤不同的 Shell 脚本中使用它,

pipeline {
    agent any
    tools {
        maven 'M2'
    }

    environment {
        stable_revision = sh(script: 'curl -H "Authorization: Basic $base64encoded" "https://xyz.sad" | jq -r "name"', returnStdout: true)
    }

    stages {
        stage('Initial-Checks') {
            steps {
          echo "Stable Revision: ${env.stable_revision}" //displays the value
          bat "sh && sh undeploy.sh"
        }}
...
}}
Run Code Online (Sandbox Code Playgroud)

这是一个示例 Shell 脚本,它有很多行,但我在仅访问上述变量时遇到问题stable_revision

#!/bin/bash
echo xyz = ${stable_revision} #### this gives the right value xyz = 22
echo xyz2 = ${stable_revision}/d ### here after the value the /d is written in new line
Run Code Online (Sandbox Code Playgroud)

例如,假设stable_revision值为22,那么在 SH 脚本中echo我得到的值为,

xyz2 = 22
 /d
Run Code Online (Sandbox Code Playgroud)

我想要的值为xyz2 = 22/d

Jns*_*Jns 6

您可以使用它.trim()来去掉尾随的换行符。

environment {
        stable_revision = sh(script: 'curl -H "Authorization: Basic $base64encoded" "https://xyz.sad" | jq -r "name"', returnStdout: true).trim()
}
Run Code Online (Sandbox Code Playgroud)

returnStdout(可选):如果选中,任务的标准输出将作为步骤值作为字符串返回,而不是打印到构建日志中。(标准错误(如果有)仍将打印到日志中。)您经常需要对结果调用 .trim() 以去掉尾随换行符。

https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#sh-shell-script