bash 如何使用 Groovy 执行带有反引号的 shell 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14282208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:14:34  来源:igfitidea点击:

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

bashshellgroovybackticks

提问by Dag

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

我无法使用 Groovy 执行带有反引号的 shell 命令。一个简化的例子:

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

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

我四处寻找并试图弄清楚如何以某种方式逃离他们,但没有运气。

回答by Faiz

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 echowith the argument

Runtime#exec(String)如果您正在调用execute()字符串,则将在下面使用java 。在这种情况下,这只是标记字符串并echo使用参数执行程序

`date`

or

或者

$(date)

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

但这是 shell (bash) 语法,必须通过 bash 执行。