Jenkins 因 grep 结果为空而失败
Jenkins fails on empty grep result
我需要在 jenkins 中过滤一个文件。只要结果不为空,过滤就会起作用。但是,如果结果输出为空,管道将失败并显示 ERROR: script returned exit code 1 Finished: FAILURE
示例:
#!groovy
pipeline {
agent any
stages {
stage ('mystage') {
steps {
script {
sh "echo '' > myfile"
sh "echo 'foo 0' >> myfile"
sh "echo 'foo 1' >> myfile"
sh "grep foo myfile"
sh "grep ba myfile"
}
}
}
}
}
输出:
+ echo ''
[Pipeline] sh
+ echo 'foo 0'
[Pipeline] sh
+ echo 'foo 1'
[Pipeline] sh
+ grep foo myfile
foo 0
foo 1
[Pipeline] sh
+ grep ba myfile
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
使用 grep ba myfile > catchoutput
将输出路由到文件不起作用。
我怎样才能输出 grep 结果,而管道在这种边缘情况下不会失败?
添加像 sh "echo 'dummyline that won't match' >> myfile"
这样的虚拟行似乎可行,但却是一种 hack。有没有干净的解决方案?
我们可以在变量中取 return 值:
def ret = sh(script: 'grep ba myfile', returnStdout: true)
更多信息:https://www.jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#code-sh-code-shell-script。
注意你也可以加上returnStatus: true
,这样jenkins step即使出现命令失败也不会失败
我需要在 jenkins 中过滤一个文件。只要结果不为空,过滤就会起作用。但是,如果结果输出为空,管道将失败并显示 ERROR: script returned exit code 1 Finished: FAILURE
示例:
#!groovy
pipeline {
agent any
stages {
stage ('mystage') {
steps {
script {
sh "echo '' > myfile"
sh "echo 'foo 0' >> myfile"
sh "echo 'foo 1' >> myfile"
sh "grep foo myfile"
sh "grep ba myfile"
}
}
}
}
}
输出:
+ echo ''
[Pipeline] sh
+ echo 'foo 0'
[Pipeline] sh
+ echo 'foo 1'
[Pipeline] sh
+ grep foo myfile
foo 0
foo 1
[Pipeline] sh
+ grep ba myfile
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
使用 grep ba myfile > catchoutput
将输出路由到文件不起作用。
我怎样才能输出 grep 结果,而管道在这种边缘情况下不会失败?
添加像 sh "echo 'dummyline that won't match' >> myfile"
这样的虚拟行似乎可行,但却是一种 hack。有没有干净的解决方案?
我们可以在变量中取 return 值:
def ret = sh(script: 'grep ba myfile', returnStdout: true)
更多信息:https://www.jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#code-sh-code-shell-script。
注意你也可以加上returnStatus: true
,这样jenkins step即使出现命令失败也不会失败