「Apache Groovy」- 运行 Shell 命令 @20210410
问题描述
在 Groovy 中,我们需要运行 Shell 命令,尤其将其当作脚本使用并配合 Git 命令时(我们知道有 JGit 类库,但是远不及命令方便,或许是我们的需求比较简单,或许是我们不愿意去研究新的事物)。
总之,我们需要在 Groovy 中调用 Shell 命令。
该笔记将记录:在 Groovy 中,如何执行 Shell 命令,以及常见操作、注意事项。
解决方案
执行命令,并获取输出:
String result = "ls -lt ".execute().text println result.toUpperCase()
执行命令,并设置超时时间:
def resultado = new StringBuilder() def error = new StringBuilder() def comando = "ls -lt".execute() //(2) comando.consumeProcessOutput(resultado, error) //(3) comando.waitForOrKill(1000) //(4) if (!error.toString().equals("")) //(5) println "error: ${error.toString()}" }
常见问题汇总
如果命令参数中包含空格(空白字符)
def cmdOutput = ['ls', '/tmp/folder with spaces'].execute().text
相关文章
「Groovy」- 彩色化输出日志
「Groovy」- 操作 HTML 文档
「Groovy」- 处理 Object 与 JSON String 之间的转换
「Apache Groovy」- 处理日期时间
「Groovy」- 处理路径地址
参考文献
Execute commands
groovy execute with parameters containing spaces - Stack Overflow