在 Jenkins 管道中如何传递 shell 脚本从标准输入读取的字符串

问题描述 投票:0回答:1

我有一个詹金斯管道。如何将字符串作为标准输入“传递”到 shell 脚本?

def getStatusJson() {
    if (this.statusJson == null)
        this.statusJson = slowHttpRequest()
    }
    return this.statusJson
}

def func1() {
    def json = getStatusJson()
    def command = ("echo '${pullRequestStatusJson}' | jq '.participants[] | select(.state=="changes_requested")' | jq '.state'")
    return sh (label: 'get PR change-requested state', script: command, returnStdout: true).trim()
}

def func2() {
    def json = getStatusJson()
    def command = ("echo '${pullRequestStatusJson}' | jq '.state'")
    return sh (label: 'get PR state', script: command, returnStdout: true).trim()
}

上面的代码失败了,很可能是因为 pullRequestStatusJson 有撇号,但无论如何,这似乎不是一个很好的解决方案。如何设置 shell 脚本的 stdin 来代替 echo?比如:

def json = getStatusJson()
def command = ("jq '.state'")
return sh (label: 'get PR state', script: command, returnStdout: true, stdin: json ).trim()
jenkins jenkins-pipeline sh stdin
1个回答
1
投票

抱歉,这已经是标准

sh
步骤所能达到的最佳效果了。您可以编写自己的包装器来接受
stdin
,但您已经知道了:) 当您将一些复杂的字符串(混合有单引号和双引号)传递给
sh
时,添加
withEnv
并让 Jenkins 进行转义会更容易:

withEnv(["MY_STDIN=$pullRequestStatusJson"]) {
    sh '''echo "${MY_STDIN}" | jq '.state' '''
}
© www.soinside.com 2019 - 2024. All rights reserved.