Home >Backend Development >Golang >How to Retrieve System Command Output in Go?
Retrieving System Command Output in Go
In Go, executing system commands and capturing their output can be achieved with various packages and approaches. This article delves into a straightforward method using the exec package.
The exec package provides a convenient way to fork processes and retrieve their output. Here's a sample code snippet:
package main import ( "fmt" "log" "os/exec" ) func main() { out, err := exec.Command("date").Output() if err != nil { log.Fatal(err) } fmt.Printf("The date is %s\n", out) }
In this example:
The exec.Command also offers another method, CombinedOutput(), which combines standard output and standard error into a single byte slice, allowing you to handle both at once.
By employing the Output() or CombinedOutput() methods, you can effortlessly capture the output of arbitrary system commands within your Go programs.
The above is the detailed content of How to Retrieve System Command Output in Go?. For more information, please follow other related articles on the PHP Chinese website!