Using groovy, how do you pipe multiple shell commands?

前端 未结 4 2144
礼貌的吻别
礼貌的吻别 2020-12-05 11:30

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 i

相关标签:
4条回答
  • 2020-12-05 11:51

    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
    0 讨论(0)
  • 2020-12-05 11:53

    If you want it async I recommend

     proc.consumeProcessOutputStream(new LineOrientedOutputStream() {
            @Override
            protected void processLine(String line) throws IOException {
               println line
            }
        }
        );
    
    0 讨论(0)
  • 2020-12-05 12:08

    You can do this to just let the shell sort it out:

    // slash string at the end so we don't need to escape ' or $
    def p = ['/bin/bash', '-c', /ps aux | grep ' foo' | awk '{print $1}'/].execute()
    p.waitFor()
    println p.text
    
    0 讨论(0)
  • 2020-12-05 12:09

    This has worked for me

    def command = '''
        ps aux | grep bash | awk '{print $1}'
    '''
    def proc = ['bash', '-c', command].execute()
    proc.waitFor()
    println proc.text
    

    If you want to run multiple commands, you can add it in the command.

    def command = '''
        ls -ltr
        cat secret
    '''
    def proc = ['bash', '-c', command].execute()
    proc.waitFor()
    println proc.text
    
    0 讨论(0)
提交回复
热议问题