Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file-io

go

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() } 
like image 376
jergason Avatar asked Sep 24 '13 16:09

jergason


People also ask

What is CMD in Golang?

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.

How do you execute a shell command in Go?

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.

What is Golang exec?

It is simply a sub-package that allows you to execute external commands using Go.


1 Answers

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() } 
like image 79
jergason Avatar answered Sep 18 '22 14:09

jergason