file - 如何从 groovy 正确调用 shell 命令

标签 file shell groovy command

我想从我的 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/

相关文章:

java - 文件输入帮助/建议

linux - 复制带有双引号和匹配模式的文件

grails - 如何检查列表是否具有相同的值?

Java File.listFiles() 无法从绝对路径检索名称

command-line - 在 Perforce 中删除文件的命令行语法是什么?

shell - 如何更改 Docker ENV var?

bash shell 脚本条件赋值

jenkins - 管道作业 - 向上游传递参数?

grails - 为什么我的TRACE会收到groovy.lang.MissingPropertyException?

java - dlmread 为大型文本文件返回单列