是否可以从管道中的sh DSL命令捕获stdout

时间:2016-04-08 19:06:12

标签: jenkins jenkins-workflow jenkins-pipeline

例如:

var output=sh "echo foo";
echo "output=$output";

我会得到:

output=0

所以,显然我得到退出代码而不是stdout。是否有可能将stdout捕获到管道变量中,这样我就可以得到: output=foo 作为我的结果?

6 个答案:

答案 0 :(得分:175)

Nowsh step支持通过提供参数returnStdout返回 stdout

// These should all be performed at the point where you've
// checked out your sources on the slave. A 'git' executable
// must be available.
// Most typical, if you're not cloning into a sub directory
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
// short SHA, possibly better for chat notifications, etc.
shortCommit = gitCommit.take(6)

请参阅this example

答案 1 :(得分:4)

试试这个:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

经过测试:

  • Jenkins ver。 2.19.1
  • Pipeline 2.4

答案 2 :(得分:3)

简短版本是:

echo sh(script: 'ls -al', returnStdout: true).result

答案 3 :(得分:1)

您也可以尝试使用此功能来捕获StdErr StdOut并返回代码。

def runShell(String command){
    def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt" 
    def output =  readFile(file: "tmp.txt")

    if (responseCode != 0){
      println "[ERROR] ${output}"
      throw new Exception("${output}")
    }else{
      return "${output}"
    }
}

注意:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name

答案 4 :(得分:0)

def列表= sh脚本:'ls -la /',returnStdout:true

参考:http://shop.oreilly.com/product/0636920064602.do第433页

答案 5 :(得分:0)

我遇到了同样的问题,并尝试了几乎所有发现的问题,之后才知道我在错误的地方尝试了它。我在步骤块中尝试过它,而它必须在环境块中。

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }