【发布时间】:2009-04-24 14:49:38
【问题描述】:
如何为groovy中字符串的execute方法提供包含空格的参数?像在 shell 中那样添加空格并没有帮助:
println 'ls "/tmp/folder with spaces"'.execute().text
这会给 ls 调用提供三个损坏的参数。
【问题讨论】:
标签: groovy
如何为groovy中字符串的execute方法提供包含空格的参数?像在 shell 中那样添加空格并没有帮助:
println 'ls "/tmp/folder with spaces"'.execute().text
这会给 ls 调用提供三个损坏的参数。
【问题讨论】:
标签: groovy
诀窍是使用列表:
println(['ls', '/tmp/folder with spaces'].execute().text)
【讨论】:
对不起,上面的技巧都不适合我。 这段可怕的代码是唯一通过的:
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
【讨论】:
对于需要常规报价处理、管道等的人来说,一个奇怪的技巧:使用bash -c
['bash','-c',
'''
docker container ls --format="{{.ID}}" | xargs -n1 docker container inspect --format='{{.ID}} {{.State.StartedAt}}' | sort -k2,1
'''].execute().text
【讨论】:
["bash","-c","your command with spaces and quotes"].execute().text
我觉得使用列表有点笨拙。
这样就可以了:
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"');
唯一的缺点是需要在所有参数周围加上引号,我可以忍受!
【讨论】:
你试过转义空格吗?
println 'ls /tmp/folder\ with\ spaces'.execute().text
【讨论】: