如何从 Jenkins Pipeline sh 脚本步骤返回 stdout 和 stderr 以及状态

Ger*_*ica 7 shell stdout stderr jenkins jenkins-pipeline

这个问题的答案受到@codeGeass对How toexecute a command in a Jenkins 2.0 Pipeline job and then return the stdout 的回答的评论的启发:

我们可以一起使用它们吗?在变量中捕获 returnStdout 并在另一个变量中捕获 returnStatus ?因为重复 sh 脚本两次并不酷

Ger*_*ica 6

要返回stdoutstderr结合状态,您可以执行以下操作:

def runScript(command) {
    script {
        sh script: "set +x ; $command 2>&1 && echo \"status:\$?\" || echo \"status:\$?\" ; exit 0", returnStdout: true
    }
}

pipeline {
    agent any

    stages {
        stage('more values from sh') {
            steps {
                script {
                    // inline
                    def stdoutAndStatus = sh script: 'set +x ; ls -a 2>&1 && echo "status:$?" || echo "status:$?" ; exit 0', returnStdout: true
                    echo "stdoutAndStatus: >$stdoutAndStatus<".trim()
                    
                    def stderrAndStatus = sh script: 'set +x ; ls notexisting 2>&1 && echo "status:$?" || echo "status:$?" ; exit 0', returnStdout: true
                    echo "stderrAndStatus: >$stderrAndStatus<".trim()
                    
                    // with function
                    echo "runScript: >${runScript('ls -a')}<".trim()
                    echo "runScript: >${runScript('ls notexisting')}<".trim()
                    
                    // failing the sh step
                    echo "runScript: >${runScript('not_existing_command')}<".trim()
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台输出

[Pipeline] stage
[Pipeline] { (more values from sh)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ set +x
[Pipeline] echo
stdoutAndStatus: >.
..
status:0
<
[Pipeline] sh
+ set +x
[Pipeline] echo
stderrAndStatus: >ls: notexisting: No such file or directory
status:2
<
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ set +x
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
runScript: >.
..
status:0
<
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ set +x
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
runScript: >ls: notexisting: No such file or directory
status:2
<
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ set +x
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
runScript: >C:/Users/jenkins/AppData/Local/Jenkins/.jenkins/workspace/SO-36956977 more values from sh@tmp/durable-af2cee22/script.sh: line 1: not_existing_command: command not found
status:127
<
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)