vaporwave_sailor
vaporwave_sailor

Reputation: 13

Jenkins/Groovy - For each item in array execute shell script with variable from item

I have an array and a function.

Function calls context.sh and executes shell command with variable I want to pass (next from array in this loop).

Target:

  1. Grep file, use item from array every loop
  2. If string is not empty (returns a value from shell script) print line with message and error
  3. Export value 'true' to variable called 'errors found'.

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

So far I cannot manage to make it check every item from array and change the value. How do I implement this?

Upvotes: 1

Views: 6447

Answers (1)

daggett
daggett

Reputation: 28564

guess you just want to exclude lines with some words from result.

just convert the list into string separated with | (pipe).

so the shell command will look like this:

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

and catch stdout into groovy variable using returnStdout parameter

so the sh call should look like:

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

Upvotes: 3

Related Questions