104

例如:

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

我会得到:

output=0

所以,显然我得到了退出代码而不是标准输出。是否可以将标准输出捕获到管道变量中,以便我可以得到: output=foo 作为我的结果?

4

7 回答 7

250

现在,该sh步骤支持通过提供参数返回标准输出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)

请参阅此示例

于 2016-08-12T07:57:45.213 回答
47

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

JENKINS-26133中所述,无法将 shell 输出作为变量获取。作为一种解决方法,建议使用从临时文件中读取的命令。所以,你的例子看起来像:

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";
于 2016-04-10T15:30:16.163 回答
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
    ...
}

测试:

  • 詹金斯版 2.19.1
  • 管道 2.4
于 2017-01-10T07:29:25.787 回答
4

您也可以尝试使用此函数来捕获 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
于 2018-12-10T15:49:23.263 回答
1

一个简短的版本是:

echo sh(script: 'ls -al', returnStdout: true).result
于 2018-05-30T11:35:47.947 回答
1

我遇到了同样的问题并尝试了几乎所有在我知道我在错误的街区尝试之后发现的所有东西。我在步骤块中尝试它,而它需要在环境块中。

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }
于 2020-07-23T10:44:12.720 回答
0
def listing = sh script: 'ls -la /', returnStdout:true

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

于 2019-12-30T11:37:20.800 回答