如何正确地从groovy调用shell命令 [英] how to call shell commands from groovy correctly

查看:9855
本文介绍了如何正确地从groovy调用shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的groovy脚本执行shell命令。
我测试了以下:

i want to execute shell commands from my groovy script. I tested the following:

"mkdir testdir".execute()

这只是工作正常。
现在我想创建一个文件,写入文件,然后打开一个文本编辑器来查看文件。

and this just works fine. Now i wanted to make a file, write something to the file and then open a text editor to view the file.

def execute(cmd) {
   def proc =  cmd.execute()
   proc.waitFor()
}

execute("touch file")
execute("echo hello > file")
execute("gedit file")

现在gedit打开正确,但在文件中没有hello字符串。
这是如何工作的?

Now gedit opens correctly but ther is no "hello" string in the file. How is this working?!?

推荐答案

您不能在行中重定向:

execute("echo hello > file")

所以没有任何东西写入文件。

So nothing gets written to the file. The easiest way to handle this is probably to wrap all your commands into a single shell script, then execute this script.

否则,你可以读取标准的输出。

Otherwise, you can read the standard output from the echo command (without the > file), and then write this to file yourself in Groovy.

或您可以:

execute( [ 'bash', '-c', 'echo hello > file' ] )

这应该作为执行方法将执行 List.execute()方法

Which should work as your execute method will just perform the List.execute() method

这篇关于如何正确地从groovy调用shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆