Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 637
Dag Avatar asked Jan 11 '13 16:01

Dag


People also ask

How do I run shell commands in Groovy?

In this environment, Groovy offers us the ability to execute commands with the help of the . execute () method of the String class and treat the output of this as if it were a chain, using all the language power.

How do I run a shell script in Groovy script?

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 backtick in shell script?

The backtick allows you to assign the output of a shell command to a variable. While this doesn't seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters: # testing=`date`

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.


1 Answers

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.

like image 128
Faiz Avatar answered Sep 19 '22 16:09

Faiz