groovy执行包含空格的参数

时间:2009-04-24 14:49:39

标签: groovy

如何在groovy中为字符串的execute方法提供包含空格的参数?只是在shell中添加一个空格也无济于事:

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

这会给ls调用提供三个破坏的参数。

5 个答案:

答案 0 :(得分:27)

诀窍是使用列表:

println(['ls', '/tmp/folder with spaces'].execute().text)

答案 1 :(得分:1)

对不起,上面没有任何技巧对我有用。 这段可怕的代码是唯一通过的代码:

    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

答案 2 :(得分:0)

对于需要常规报价处理,管道等操作的人来说,这是一个奇怪的技巧:使用bash -c

['bash','-c',
'''
docker container ls --format="{{.ID}}" | xargs -n1 docker container inspect --format='{{.ID}} {{.State.StartedAt}}' | sort -k2,1
'''].execute().text

答案 3 :(得分:-2)

使用列表对我来说有点笨拙。

这可以胜任:

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"')

更复杂的例子:

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

唯一的缺点是需要在所有的args周围加上引号,我可以忍受!

答案 4 :(得分:-4)

你试过逃避空间吗?

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