Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File 如何从groovy正确调用shell命令_File_Shell_Groovy_Command - Fatal编程技术网

File 如何从groovy正确调用shell命令

File 如何从groovy正确调用shell命令,file,shell,groovy,command,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")

我想从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
命令(不带
>文件
)读取标准输出,然后自己在Groovy中将其写入
文件

或者你可以:

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

它应该可以工作,因为您的
execute
方法只能执行我对
groovy
一无所知;也就是说,有没有一种方法可以告诉
execute
方法在执行之前将命令行传递给shell进行处理,比如Python
subprocess
模块的
shell=True
选项?@chepner实际上,你是对的……有一种方法。。。补充到答案中