Groovy执行脚本命令shell command

1): 直接执行一个字符串语句,executing a string

A string can be executed in the standard java way:
def command = """executable arg1 arg2 arg3"""// Create the String
def proc = command.execute()                 // Call *execute* on the string
proc.waitFor()                               // Wait for the command to finish

// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

Gotchas: Take care if you wish to pass a quoted argument that contains white space – it will be split into multiple arguments, e.g.:

"""executable "first with space" second""".execute()

will invoke executable with the following arguments:

  • arg1 = "first
  • arg2 = with
  • arg3 = space"
  • arg4 = second

In such a case, you may prefer to use one of the array or list of String variations, e.g.:

["executable", "first with space", "second"].execute()

2) Processing shell command with piping in groovy script, 在groovy 脚本中使用管道功能

def proc = "ffmpeg -i /tmp/sample.m4a -f ffmetadata 2>&1 | grep Duration".execute()

是不行的,the '2>1&1' bit is shell functionality, and Groovy processes don't invoke the shell, they just start a program. If you really need it, you should do something like:

 

def proc1 = ['/bin/bash', '-c', '/usr/local/bin/ffmpeg -i /tmp/sample.m4a -f ffmetadata 2>&1'].execute()

or similar - do some experimenting. That is, you need to call the shell with the command you want executed as argument.

3): using ant builder's exec task

Ant has an exec task and it be accessed from the AntBuilder object

def ant = new AntBuilder()   // create an antbuilder
ant.exec(outputproperty:"cmdOut",
             errorproperty: "cmdErr",
             resultproperty:"cmdExit",
             failonerror: "true",
             executable: '/opt/myExecutable') {
                             arg(line:"""*"first with space"* second""")
             }
println "return code:  ${ant.project.properties.cmdExit}"
println "stderr:         ${ant.project.properties.cmdErr}"
println "stdout:        ${ ant.project.properties.cmdOut}"

转载于:https://my.oschina.net/jjyuangu/blog/1815945

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值