使用 groovy,您如何通过管道传输多个 shell 命令? [英] Using groovy, how do you pipe multiple shell commands?

查看:25
本文介绍了使用 groovy,您如何通过管道传输多个 shell 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Groovy 和它的 java.lang.Process 支持,我如何将多个 shell 命令连接在一起?

Using Groovy and it's java.lang.Process support, how do I pipe multiple shell commands together?

考虑这个 bash 命令(并假设你的用户名是 foo):

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.

使用 Groovy,ProcessGroovyMethods 文档和代码说我应该能够这样做以达到相同的结果:

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

一旦我开始管道, println 就不会打印出任何东西.

As soon as I start piping, the println does not print out any anything.

想法?

推荐答案

这对我有用:

def p = 'ps aux'.execute() | 'grep foo'.execute() | ['awk', '{ print $1 }'].execute()
p.waitFor()
println p.text

不知什么原因,awk 的参数不能只用一个字符串发送(我不知道为什么!也许 bash 引用了不同的东西).如果您使用命令转储错误流,您将看到与 awk 脚本编译相关的错误.

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.

编辑:事实上,

  1. "-string-".execute() 委托给 Runtime.getRuntime().exec(-string-)
  2. 处理包含带有 ' 或 " 空格的参数是 bash 的工作.Runtime.exec 或操作系统不知道引号
  3. 执行"grep ' foo'".execute() 执行命令grep,以'为第一个参数,foo'作为第二个:这是无效的.awk 也一样
  1. "-string-".execute() delegate to Runtime.getRuntime().exec(-string-)
  2. It's bash job to handle arguments containing spaces with ' or ". Runtime.exec or the OS are not aware of the quotes
  3. Executing "grep ' foo'".execute() execute the command grep, with ' as the first parameters, and foo' as the second one : it's not valid. the same for awk

这篇关于使用 groovy,您如何通过管道传输多个 shell 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆