为什么这个curl命令在groovy中执行时会失败?

Bri*_*ian 3 groovy curl

这个curl命令在终端中有效,但在groovy中失败。我从另一个问题中添加了错误并尝试理解它失败的原因。

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()
Run Code Online (Sandbox Code Playgroud)

输出为“curl:尝试‘curl --help’或‘curl --manual’以获取更多信息”

cfr*_*ick 6

不要使用字符串来执行,因为 Groovy 会根据空格进行分割。您必须将“shell 命令”作为单个参数传递给sh -c. 所以现在你 a)curl和 url 之间缺少空格 b) 这最终将成为两个参数(并且你不能引用它)。

使用字符串列表代替:

['sh', '-c', "curl 'http://...'"].execute()
Run Code Online (Sandbox Code Playgroud)

另外,如果您只想要 url 的内容并且不需要花哨的东西(超时、身份验证……),您也可以这样做:

"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts".toURL().text
Run Code Online (Sandbox Code Playgroud)