How can I use Groovy to execute a shell command that has backticks?

Dag picture Dag · Jan 11, 2013 · Viewed 11.6k times · Source

I’m unable to use Groovy to execute a shell command that has backticks. A simplified example:

println "echo `date`".execute().text

I searched around and tried to figure out how to escape them somehow, but without luck.

Answer

Faiz picture Faiz · Jan 11, 2013

What happens if you try:

println ["bash", "-c", "echo `date`"].execute().text

My guess would be that with

"echo `date`".execute() 

java's Runtime#exec(String) would be used underneath, if you were calling execute() on a String. In which case, this simply tokenizes the string and executes the program echo with the argument

`date`

or

$(date)

but that's shell (bash) syntax, and must be executed via bash.