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

Capture the output of sh command in the declarative Jenkins pipeline

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

如何设置全局变量?

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

如果你想正确捕获 sh step 的输出,那么你需要替换

b = sh 'ls -l /'

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

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