为什么这个 curl 命令在 groovy 中执行时会失败? [英] Why does this curl command fail when executed in groovy?
问题描述
此 curl 命令在终端中有效,但在 groovy 中失败.我从另一个问题中添加了错误并退出,以尝试了解它失败的原因.
This curl command works in the terminal but fails in groovy. I added the err and out out from another question to try and understand why it fails.
def initialSize = 4096
def out = new ByteArrayOutputStream(initialSize)
def err = new ByteArrayOutputStream(initialSize)
def process = "sh -c curl'https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts'".execute()
process.consumeProcessOutput(out, err)
process.waitFor()
println process.text
println err.toString()
println out.toString()
输出是curl: try 'curl --help' or 'curl --manual' 以获取更多信息"
The output is "curl: try 'curl --help' or 'curl --manual' for more information"
推荐答案
不要使用字符串来执行,因为 Groovy 会在空白处进行拆分.您必须将shell 命令"作为 单个 参数传递给 sh -c
.所以现在你 a) 在 curl
和 url 之间缺少空格和 b) 这将最终成为两个参数(你不能引用它).
Don't use string for execute, as Groovy will split on whitespace. You have to pass the "shell command" as a single argument to sh -c
. So right now you a) lack a space between curl
and the url and b) this will end up as two arguments (and you can not quote for that).
改用字符串列表:
['sh', '-c', "curl 'http://...'"].execute()
还有一个旁注:如果你只想要一个 url 的内容而不需要花哨的东西(超时,身份验证,...),你也可以这样做:
Also on a sidenote: if you just want the content of a url and don't need fancy things (timeouts, auth, ...), you can just as well do:
"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts".toURL().text
这篇关于为什么这个 curl 命令在 groovy 中执行时会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!