tags:

views:

433

answers:

3

How do I provide arguments containing spaces to the execute method of strings in groovy? Just adding spaces like one would in a shell does not help:

println 'ls "/tmp/folder with spaces"'.execute().text

This would give three broken arguments to the ls call.

A: 

did you tried escaping spaces?

println 'ls /tmp/folder\ with\ spaces'.execute().text
dfa
Yes, but it didn't work.
Johan Lübcke
A: 

The trick was to use a list:

println(['ls', '/tmp/folder with spaces'].execute().text)
Johan Lübcke
A: 

Using a List feels a bit clunky to me.

This would do the job:

def exec(act) { 
 def cmd = []
 act.split('"').each { 
   if (it.trim() != "") { cmd += it.trim(); }
 }
 return cmd.execute().text
}

println exec('ls "/tmp/folder with spaces"')

More complex example:

println runme('mysql "-uroot" "--execute=CREATE DATABASE TESTDB; USE TESTDB; \\. test.sql"');

The only downside is the need to put quotes around all your args, I can live with that!

Richard Pearce