Execute a command in Linux using Java and fetch the output

前端 未结 3 1427
野趣味
野趣味 2020-12-30 17:26

I am using Groovy to execute commands on my Linux box and get back the output, but I am not able to use | pipes somehow (I think) or maybe it is not waiting for

3条回答
  •  有刺的猬
    2020-12-30 17:57

    You cannot do pipes or redirects using String.execute(). This doesn't work in Java, so it doesn't work in Groovy either...

    You can use Process.pipeTo with Groovy to simplify things:

    Process proca = 'uname -a'.execute()
    Process procb = 'awk {print\$2}'.execute()
    
    (proca | procb).text
    

    A more generic version could be:

    String process = 'uname -a | awk {print\$2}'
    
    // Split the string into sections based on |
    // And pipe the results together
    Process result = process.tokenize( '|' ).inject( null ) { p, c ->
      if( p )
        p | c.execute()
      else
        c.execute()
    }
    // Print out the output and error streams
    result.waitForProcessOutput( System.out, System.out )
    

提交回复
热议问题