Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

bash - Using groovy, how do you pipe multiple shell commands?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,

  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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...