Pass List<String> to exec task?

Is it possible to pass a List to the exec task somehow?

I have:

def runCmd(List<String> cmd) {
    def stdout = new ByteArrayOutputStream()
    exec {
        executable "sh"
        //args cmd
        args "-c", cmd        
    }
}

That I call with e.g.:

runCmd(["git", "push", "origin", "master"])

But fails with :

Starting process 'command 'sh''. Working directory: /home/user/samples/my-app Command: sh -c [git, push, origin, master]
Successfully started process 'command 'sh''
sh: 1: [git,: not found

And I have tried numerous different permutations of pass/reading that List but so far no luck.

You’ll need create a new list containing “-c” plus your extra args. Groovy has overridden the “+” operator for list so you can do

exec {
   args(['-c'] + cmd) 
} 

Or alternatively

def myArgs = ['-c'] 
myArgs.addAll cmd
exec {
   args myArgs
} 

I also find it more readable to do

runCmd 'git push origin master'.split(' ')

The groovy spread operator is another option that should work for this instance:

args "-c", *cmd
2 Likes