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

Jes*_*e S 74 jenkins jenkins-workflow jenkins-pipeline

例如:

var output=sh "echo foo";
echo "output=$output";
Run Code Online (Sandbox Code Playgroud)

我会得到:

output=0
Run Code Online (Sandbox Code Playgroud)

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

ilo*_*ahz 198

现在,该sh步骤支持通过提供参数返回stdoutreturnStdout.

// 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)
Run Code Online (Sandbox Code Playgroud)

这个例子.

  • 注意这个答案的`.trim()`部分,否则你可能会在行的末尾得到一个换行符 (8认同)
  • 将`--short`附加到`rev-parse`可以直接获得短哈希 (2认同)
  • 不知道是什么导致失败,但我不得不将输出转换为字符串也像这样`gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').toString().trim()` (2认同)
  • @Vano 引用了 Groovy 方法 take(),在这种情况下它将获取前 6 个字符。http://docs.groovy-lang.org/docs/groovy-2.3.2/html/api/org/codehaus/groovy/runtime/StringGroovyMethods.html#take(java.lang.CharSequence,%20int) (2认同)

小智 44

注意:已经解决了链接的Jenkins问题.

如在JENKINS-26133中提到的那样,不可能将shell输出作为变量.作为一种解决方法,建议使用临时文件中的写入读取.所以,你的例子看起来像:

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";
Run Code Online (Sandbox Code Playgroud)

  • 对于新手,请参阅下面的答案http://stackoverflow.com/a/38912813/345845,这是因为新的`returnStdout`参数传递给`sh`步骤变得更容易了. (20认同)
  • 唯一一次,这实际上是一个很好的答案,如果你需要**shell命令中的`stdout`和`exit status`.其他时候,使用`returnStdout`参数. (3认同)
  • "不可能将shell输出作为变量" - 不是这样.这是一个黑客,正确的答案是returnStdout. (2认同)

MET*_*IJI 5

尝试这个:

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
    ...
}
Run Code Online (Sandbox Code Playgroud)

测试于:

  • 詹金斯版本。2.19.1
  • 管道2.4


Gal*_*one 5

您也可以尝试使用此函数来捕获 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}"
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name
Run Code Online (Sandbox Code Playgroud)