我想从我的 groovy 脚本中执行 shell 命令。
我测试了以下内容:
"mkdir testdir".execute()
这很好用。
现在我想制作一个文件,向文件中写入一些内容,然后打开一个文本编辑器来查看该文件。
def execute(cmd) {
def proc = cmd.execute()
proc.waitFor()
}
execute("touch file")
execute("echo hello > file")
execute("gedit file")
现在 gedit 可以正确打开,但文件中没有“hello”字符串。
这是如何工作的?!?
最佳答案
您不能在行中进行重定向:
execute("echo hello > file")
所以没有任何东西被写入文件。处理此问题的最简单方法可能是将所有命令包装到单个 shell 脚本中,然后执行该脚本。
否则,您可以从
echo
读取标准输出命令(没有 > file
),然后将其写入 file
自己在 Groovy 中。或者你可以这样做:
execute( [ 'bash', '-c', 'echo hello > file' ] )
哪个应该作为您的
execute
方法只会执行 the List.execute()
method
关于file - 如何从 groovy 正确调用 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12512919/