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

例如:

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

我会得到:

output=0

显然我得到的是出口代码而不是标准输出。有没有可能将标准输出捕获到管道变量中,这样我就可以得到: output=foo 结果呢?

140012 次浏览

Note: The linked Jenkins issue has since been solved.

As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";

Now, the sh step supports returning stdout by supplying the parameter returnStdout.

// 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)

See this example.

Try this:

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
...
}

Tested on:

  • Jenkins ver. 2.19.1
  • Pipeline 2.4

A short version would be:

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

You can try to use as well this functions to capture StdErr StdOut and return code.

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}"
}
}

Notice:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name
def listing = sh script: 'ls -la /', returnStdout:true

Reference : http://shop.oreilly.com/product/0636920064602.do Page 433

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

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