33

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.

Johan Lübcke
  • 19,666
  • 8
  • 38
  • 35

5 Answers5

34

The trick was to use a list:

println(['ls', '/tmp/folder with spaces'].execute().text)
Johan Lübcke
  • 19,666
  • 8
  • 38
  • 35
  • 1
    In case the command is dynamically generated or asked to the user this solution is not working. Surely cannot be so difficult parsing keeping in count the quotes... – Uberto Nov 26 '12 at 17:28
1

Sorry man, none of the tricks above worked for me. This piece of horrible code is the only thing that went thru:

    def command = 'bash ~my_app/bin/job-runner.sh -n " MyJob today_date=20130202 " ' 
    File file = new File("hello.sh")
    file.delete()       
    file << ("#!/bin/bash\n")
    file << (command)
    def proc = "bash hello.sh".execute()                 // Call *execute* on the file
ihadanny
  • 4,377
  • 7
  • 45
  • 76
1

One weird trick for people who need regular quotes processing, pipes etc: use bash -c

['bash','-c',
'''
docker container ls --format="{{.ID}}" | xargs -n1 docker container inspect --format='{{.ID}} {{.State.StartedAt}}' | sort -k2,1
'''].execute().text
Jakub Bochenski
  • 3,113
  • 4
  • 33
  • 61
  • 2
    simply said: `["bash","-c","your command with spaces and quotes"].execute().text` – lepe Dec 22 '20 at 11:56
-2

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!

-4

did you tried escaping spaces?

println 'ls /tmp/folder\ with\ spaces'.execute().text
dfa
  • 114,442
  • 31
  • 189
  • 228