首页 > 解决方案 > Jenkins/Groovy - 对于数组中的每个项目,使用项目中的变量执行 shell 脚本

问题描述

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

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

目标:

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

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." 
}

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

标签: javaarraysgroovyjenkins-pipeline

解决方案


猜你只是想从结果中排除带有一些单词的行。

只需将转换为用(管道)list分隔的字符串。|

所以shell命令看起来像这样:

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

并使用returnStdout 参数将标准输出捕获到 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}"
}

推荐阅读