I am trying to run a shell command, capture stdout and write that output to a file. However, I seem to be missing a few steps, as the file I am trying to write is empty when the program exists. How can I capture the stdout of the command and write that to a file?
package main import ( "bufio" "io" "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() stdoutPipe, err := cmd.StdoutPipe() if err != nil { panic(err) } writer := bufio.NewWriter(outfile) err = cmd.Start() if err != nil { panic(err) } go io.Copy(writer, stdoutPipe) cmd.Wait() }
Overview. Package cmd runs external commands with concurrent access to output and status. It wraps the Go standard library os/exec. Command to correctly handle reading output (STDOUT and STDERR) while a command is running and killing a command. All operations are safe to call from multiple goroutines.
Execute Shell Command Using the os/exec Package in Go It provides two functions that can be used to do this: Command, which creates the cmd object, and Output, which executes the command and returns the standard output. Output: Copy It will return the location of your current working directory.
It is simply a sub-package that allows you to execute external commands using Go.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With