title: return cmd stdout and stderr as string instead of printing to console in golang
body: <p>I am executing bash commands from a <code>golang</code> application. Now the <code>stdout</code> and <code>stderr</code> go directly to console:</p>
  
  <pre><code>cmd.Stdout = os.Stdout 
  cmd.Stderr = os.Stderr
  </code></pre>
  
  <p>But I would like <code>stdout</code> and <code>stderr</code> to be returned as string variables from the <code>runBashCommandAndKillIfTooSlow</code> function without printing to the console immediately. 
  How to implement this?</p>
  
  <p>The code:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "log"
      "os"
      "os/exec"
      "time"
  )
  
  func main() {
      ok, outString, errString := runBashCommandAndKillIfTooSlow("ls -la", 2000)
      fmt.Println("ok")
      fmt.Println(ok)
      fmt.Println("outString")
      fmt.Println(outString)
      fmt.Println("errString")
      fmt.Println(errString)
  }
  
  /*
  run bash command and kill it if it works longer than "killInMilliSeconds" milliseconds
  */
  func runBashCommandAndKillIfTooSlow(command string, killInMilliSeconds time.Duration) (okResult bool, stdout, stderr string) {
      fmt.Println("running bash command...")
      fmt.Println(command)
      cmd := exec.Command("sh", "-c", command)
  
      cmd.Stdout = os.Stdout // cmd.Stdout -&gt; stdout
      cmd.Stderr = os.Stderr // cmd.Stderr -&gt; stderr
  
      okResult = true
  
      err := cmd.Start()
      log.Printf("Waiting for command to finish...")
      done := make(chan error, 1)
      go func() {
          done &lt;- cmd.Wait()
      }()
      select {
      case &lt;-time.After(killInMilliSeconds * time.Millisecond):
          if err := cmd.Process.Kill(); err != nil {
              log.Fatal("failed to kill: ", err)
              okResult = false
          }
          &lt;-done // allow goroutine to exit
          // log.Println("process killed")
      case err := &lt;-done:
  
          if err != nil {
              log.Printf("process done with error = %v", err)
              okResult = false
          }
      }
      if err != nil {
          log.Fatal(err)
          okResult = false
      }
      return
  }
  </code></pre>
  
  <p>By the way, the program should keep its ability to kill the bash command if it was too slow (<code>killInMilliSeconds</code> parameter).</p>