Thursday, December 8, 2016

Executing command-line using Groovy

Running command-line executions through Groovy may at first seem straight-forward. But after thoroughly stepping through a real world example, I've found the need to write up a function  that will make this process a little easier, as shown in the code below:

       * Execute on the command line  
       * @param command  
       * @return  
      private String execCommand(Object command, OutputStream os=null, Boolean doLog = true, Boolean ignoreStdErr = false) {  
           boolean doReturn = false  
           if (os == null) {  
                os = new ByteArrayOutputStream()  
                doReturn = true  
           ByteArrayOutputStream serr = new ByteArrayOutputStream()  
           if (doLog) {  
      "Running command: "+command)  
           Process p = command.execute()  
           p.consumeProcessOutput(os, serr)  
           if (! ignoreStdErr && serr.size() > 0) {  
                throw new Exception(serr.toString())  
           if (doReturn)  
                return new String(os.toString())  
                return null  

No comments:

Post a Comment