In golang how can I write the stdout of an exec.Cmd to a file?

Thanks to KirkMcDonald on the #go-nuts irc channel, I solved this by assigning the output file to cmd.Stdout, which means that stdout writes directly to the file. It looks like this:

package main

import (
    "os"
    "os/exec"
)

func main() {

    cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")

    // open the out file for writing
    outfile, err := os.Create("./out.txt")
    if err != nil {
        panic(err)
    }
    defer outfile.Close()
    cmd.Stdout = outfile

    err = cmd.Start(); if err != nil {
        panic(err)
    }
    cmd.Wait()
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)