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
  • 18,496
  • 8
  • 36
  • 35

5 Answers5

30

The trick was to use a list:

println(['ls', '/tmp/folder with spaces'].execute().text)
Johan Lübcke
  • 18,496
  • 8
  • 36
  • 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,067
  • 5
  • 43
  • 68
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
  • 2,953
  • 4
  • 31
  • 58
  • 1
    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
  • 111,277
  • 30
  • 187
  • 226