In a Jenkins pipeline, I am trying to retrieve the output of a shell script into a variable.
Example
list_test = sh(script:'ls | grep test', returnStdout:true).trim()
list_test.each { test ->
method(test)
}
This works fine as long as there is indeed an output. The problem is when the output of 'ls | grep test' is empty.
I end up with an error.
So far, the only workaround I found was:
try {
list_test = sh(script:'ls | grep test', returnStdout:true).trim()
}
catch (Exception ex) {
println("output is empty")
}
if (list_test) {
list_test.each { test ->
method(test)
}
}
Would there be any better way to handle that kind of issue ?
CodePudding user response:
if grep is unable to find string, it will return non-zero exit code.
You can use something like that:
(ls|grep test)||echo "nothing found"
or you can use any command (replace 'sleep 1' with your favorite command), if you do not need any output:
(ls|grep test)||sleep 1