詹金斯/格罗维(Jenkins / Groovy)-对于数组中的每个项目,使用带有项目中变量的shell脚本

时间:2018-08-29 11:49:24

标签: java arrays groovy jenkins-pipeline

我有一个数组和一个函数。

函数调用context.sh并使用要传递的变量执行shell命令(此循环中数组的下一个)。

目标:

  1. Grep文件,每个循环都要使用数组中的项
  2. 如果字符串不为空(从shell脚本返回一个值),则打印行并显示消息和错误消息
  3. 将值“ true”导出到名为“发现错误”的变量。

def grepLogs(String) {

    def errorsFound = false

List<String> list = new ArrayList<String>()
list.add("some-exclude")
list.add("anotherone")
list.add("yes")

for (String item : list) {
    System.out.println(item)
    context.sh "errorFinder=$(cat logfile.log | egrep 'error|ERROR'| grep -v ${list()})"
    if (errorFinder) {
        println "Errors in log file " + errorFinder
        errorsFound = true
    }
}

    println "No errors found." 
}

到目前为止,我无法使它检查数组中的每个项目并更改值。我该如何实现?

1 个答案:

答案 0 :(得分:1)

猜测您只想从结果中排除带有某些单词的行。

只需将list转换成用|分隔的字符串(竖线)。

因此shell命令将如下所示:

cat logfile.log | grep 'error|ERROR'| grep -v 'some-exclude|anotherone|yes'

使用returnStdout parameter

将stdout捕获到groovy变量中

因此sh调用应类似于:

def list = [ "some-exclude", "anotherone", "yes" ]
def cmd = "cat logfile.log | grep 'error|ERROR'| grep -v '${ list.join('|') }'"
def errors = sh( returnStdout: true, script: cmd )
if( errors.trim() ){
    println "errors found: ${errors}"
}