07_05_GuyT
07_05_GuyT

Reputation: 2887

Run loop command inside shell in groovy

I use the following command which work as expected

def before(Map<String, String> params) {
  sh """

  make ${params.get('arg')}
  """
}

Now I need to modify it a bit to run with loop and I get complication error

def before(Map<String, String> params) {
  sh """

  params.each{ k, v -> make ${v} }
  """
}

Any idea how to resolve this ? I try to add { } without success

Upvotes: 1

Views: 2323

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42264

You see a compilation error because the body of the string you have passed to sh step contains a part that is not recognizable by bash (this part: params.each{ k, v -> make ${v} }).

You can tackle this from a different perspective: you can collect all map entries to a list of make ${arg} commands, and you can pass it to sh step after you join all commands using newline character \n. Consider the following example:

def before(Map<String, String> map) {
    sh(map.collect { k,v -> "make ${v}" }.join("\n"))
}

before([arg1: "foo", arg2: "bar"])

The code that gets executed in sh step is an equivalent of something like this:

sh """
    make foo
    make bar
"""

Update: executing multiple commands inside """ block

If you want to apply the solution shown earlier inside """ block you may try to use something like this:

def before(Map<String, String> map) {
    sh """

    # Run any command beforehand 

    ${map.collect { k,v -> "make ${v}" }.join(" && ")}
    """
}

This approach will allow you to put any bash command before the execution of a chain of commands like

make foo && make bar && make 123 

You could use a different joiner than && (e.g. \n like in the previous example). However, chaining commands with && might be better, because if one of them fails it will prevent next commands from running.

Upvotes: 2

Related Questions