在声明性Jenkins管道中捕获sh命令的输出

时间:2019-02-14 10:29:29

标签: groovy jenkins-pipeline jenkins-declarative-pipeline

在下面的代码中,我试图将'ls -l /'结果分配给b全局变量,但是,当我尝试打印其中的内容时,结果是null. < / p>

如何设置全局变量?

def b = [:]
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script{
                    b = sh 'ls -l /'
                    println "b:"+b
                }
            }
        }
    }
}

这是结果:

[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ ls -l /
total 24
drwxr-xr-x   2 root root 4096 Jan 18 11:49 bin
drwxr-xr-x   2 root root    6 Oct 20 10:40 boot
drwxr-xr-x   5 root root  360 Jan 21 10:00 dev
drwxr-xr-x   1 root root   77 Jan 21 10:00 etc
drwxr-xr-x   2 root root    6 Oct 20 10:40 home
drwxr-xr-x   8 root root   96 Jan 18 11:49 lib
drwxr-xr-x   2 root root   34 Jan 18 11:49 lib64
drwxr-xr-x   2 root root    6 Dec 26 00:00 media
drwxr-xr-x   2 root root    6 Dec 26 00:00 mnt
drwxr-xr-x   2 root root    6 Dec 26 00:00 opt
dr-xr-xr-x 276 root root    0 Jan 21 10:00 proc
drwx------   1 root root   76 Feb 12 17:32 root
drwxr-xr-x   1 root root   21 Jan 21 10:00 run
drwxr-xr-x   2 root root 4096 Jan 18 11:49 sbin
drwxr-xr-x   2 root root    6 Dec 26 00:00 srv
dr-xr-xr-x  13 root root    0 Feb  6 02:34 sys
drwxrwxrwt   1 root root 4096 Feb 13 15:18 tmp
drwxr-xr-x   1 root root   32 Dec 26 00:00 usr
drwxr-xr-x   1 root root   39 Jan 21 10:00 var
[Pipeline] echo
b:null
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

如您所见,b变量始终设置为null

1 个答案:

答案 0 :(得分:2)

如果您想正确捕获sh step的输出,则需要替换

b = sh 'ls -l /'

使用

b = sh script: 'ls -l /', returnStdout: true

sh步骤的默认行为是将结果打印到控制台,因此,如果要更改其行为,则需要将returnStdout参数显式设置为true