How to properly invoke shell commands from groovy

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

"mkdir testdir".execute()

and it just works great. Now I wanted to create a file, write something to a 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")

Now gedit opens correctly, but ther is not the "hello" line in the file. How it works?!?

+5
source share
1 answer

You cannot redirect a string:

execute("echo hello > file")

Therefore, nothing is written to the file. The easiest way to handle this is probably to wrap all your commands in one shell script, and then execute that script.

echo ( > file), file Groovy.

:

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

execute, List.execute()

+4

All Articles