car*_*rmo 5 groovy jenkins-pipeline jenkins-declarative-pipeline
在下面的代码中,我试图将 'ls -l /' 结果分配给b
全局变量,但是,当我尝试打印其中的内容时,结果是null.
如何设置全局变量?
def b = [:]
pipeline {
agent any
stages {
stage('Build') {
steps {
script{
b = sh 'ls -l /'
println "b:"+b
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是结果:
[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
Run Code Online (Sandbox Code Playgroud)
如您所见,b
变量始终设置为null
。
如果要正确捕获sh
步骤的输出,则需要替换
b = sh 'ls -l /'
Run Code Online (Sandbox Code Playgroud)
和
b = sh script: 'ls -l /', returnStdout: true
Run Code Online (Sandbox Code Playgroud)
sh
step的默认行为是它将结果打印到控制台,所以如果你想改变它的行为,你需要显式地将returnStdout
参数设置为true
.
归档时间: |
|
查看次数: |
3148 次 |
最近记录: |