Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy execute "cp *" shell command

Tags:

groovy

I want to copy text files and only text files from src/ to dst/

groovy:000> "cp src/*.txt dst/".execute().text       
===> 
groovy:000> 

You can see the command executes w/out error but the file src/test.txt does not get copied to dst/

This also fails:

groovy:000> "cp src/* dst/".execute().text       
===> 
groovy:000> 

However...

"cp src/this.txt dst/".execute().text

works

Also,

"cp -R src/ dst".execute().text

works

Why dose the wild card seem to cause my command to silently fail?

like image 207
JJohnson Avatar asked Oct 08 '08 15:10

JJohnson


People also ask

How do I run shell command in Groovy?

Executing shell commands using Groovy is very easy. For example If you want to execute any unix/linux command using groovy that can be done using execute() method and to see the output of the executed command we can append text after it.

What is Groovy shell?

A Groovy shell is a command-line application that lets you evaluate Groovy expressions, functions, define classes and run Groovy commands. The Groovy shell can be launched in Groovy projects.

How do I run a Windows command in Groovy?

The 'cmd /c' at the start invokes the Windows command shell. Since mvn. bat is a batch script you need this. For Unix you can invoke the system shell.


1 Answers

Thanks tedu for getting me half way there.

I believe the reason that his solution didn't work was because of an 'escaping' issue.

For instance...

"sh -c 'ls'".execute()

works. But...

"sh -c 'ls '".execute()

does not.

There is probably a way to escape it properly in line there but the workaround I'm using is to pass a string array to Runtime.getRuntime().exec

command = ["sh", "-c", "cp src/*.txt dst/"]
Runtime.getRuntime().exec((String[]) command.toArray())

works beautifully!

like image 185
JJohnson Avatar answered Oct 08 '22 19:10

JJohnson