Home >Backend Development >Golang >How to Reliably Capture and Save Golang `exec` Command Output to a File?
When executing commands in Golang using the exec package, you may encounter situations where you want to capture the stdout and write it to a file. Here's a detailed guide on how to achieve this:
The initial approach involved creating a stdout pipe, setting up a writer, starting the command, and then copying the stdout into the file. However, this method occasionally resulted in an empty output file.
Thanks to insights from KirkMcDonald on the #go-nuts IRC channel, a simpler solution emerged. By assigning the output file directly to cmd.Stdout, the command's stdout can be written directly to the file. Here's the revised code:
package main import ( "os" "os/exec" ) func main() { // Create the command to be executed cmd := exec.Command("echo", "'WHAT THE HECK IS UP'") // Open the output file for writing outfile, err := os.Create("./out.txt") if err != nil { panic(err) } defer outfile.Close() // Assign the output file to the command's stdout cmd.Stdout = outfile // Start the command and wait for it to finish err = cmd.Start(); if err != nil { panic(err) } cmd.Wait() }
With this improvement, the contents of the command's stdout will be written directly to the specified file. The file will no longer be empty, providing the expected output.
The above is the detailed content of How to Reliably Capture and Save Golang `exec` Command Output to a File?. For more information, please follow other related articles on the PHP Chinese website!