使用groovy,你如何管理多个shell命令? [英] Using groovy, how do you pipe multiple shell commands?
问题描述
使用Groovy和它的 java.lang.Process
支持,我如何将多个shell命令集合在一起?
考虑这个bash命令(并且假设你的用户名是 foo
):
ps aux | grep'foo'| awk'{print $ 1}'
这会打印出用户名 - 一行用于与您用户帐户。
使用Groovy, ProcessGroovyMethods 文档和代码说我应该可以做这可以达到相同的结果:
pre presp aux.execute()| grep'foo'。execute()| awk{print $ 1}'。execute()
p.waitFor()
println p.text
但是,除此之外,我无法获得任何文本输出:
def p =ps aux.execute()
p.waitFor()
println p.text
只要我开始管道,println不会打印任何东西。
想法?
def p ='ps aux'解决方案
.execute()| 'grep foo'.execute()| ['awk','{print $ 1}']。execute()
p.waitFor()
println p.text
由于一个未知的原因,awk的参数不能只用一个字符串发送(我不知道为什么!也许bash引用的是不同的东西)。如果您使用命令转储错误流,则会看到与编译awk脚本相关的错误。
编辑:实际上,
-
- string - 。execute()
委托给Runtime.getRuntime()。exec(-string - )
- 这是bash工作,用于处理包含空格的参数。操作系统不知道引号
- 执行
grep'foo'。execute()
执行命令grep,'
作为第一个参数,foo'
作为第二个参数:它是无效的。 >
Using Groovy and it's java.lang.Process
support, how do I pipe multiple shell commands together?
Consider this bash command (and assume your username is foo
):
ps aux | grep ' foo' | awk '{print $1}'
This will print out usernames - one line for some processes related to your user account.
Using Groovy, the ProcessGroovyMethods documentation and code says I should be able to do this to achieve the same result:
def p = "ps aux".execute() | "grep ' foo'".execute() | "awk '{print $1}'".execute()
p.waitFor()
println p.text
However, I can't get any text output for anything other than this:
def p = "ps aux".execute()
p.waitFor()
println p.text
As soon as I start piping, the println does not print out any anything.
Thoughts?
This works for me :
def p = 'ps aux'.execute() | 'grep foo'.execute() | ['awk', '{ print $1 }'].execute()
p.waitFor()
println p.text
for an unknown reason, the parameters of awk can't be send with only one string (i don't know why! maybe bash is quoting something differently). If you dump with your command the error stream, you'll see error relative to the compilation of the awk script.
Edit : In fact,
"-string-".execute()
delegate toRuntime.getRuntime().exec(-string-)
- It's bash job to handle arguments containing spaces with ' or ". Runtime.exec or the OS are not aware of the quotes
- Executing
"grep ' foo'".execute()
execute the command grep, with'
as the first parameters, andfoo'
as the second one : it's not valid. the same for awk
这篇关于使用groovy,你如何管理多个shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!