I'm looking to execute a shell command in Go and get the resulting output as a string in my program. I saw the Rosetta Code version:
package main import "fmt" import "exec" func main() { cmd, err := exec.Run("/bin/ls", []string{"/bin/ls"}, []string{}, "", exec.DevNull, exec.PassThrough, exec.PassThrough) if (err != nil) { fmt.Println(err) return } cmd.Close()
But this doesn't capture the actual standard out or err in a way that I can programatically access - those still print out to the regular stdout / stderr. I saw that using Pipe as the out or err could help elsewhere, but no example of how to do so. Any ideas?
It is simply a sub-package that allows you to execute external commands using Go.
In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay.
The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).
The package "exec" was changed a little bit. The following code worked for me.
package main import ( "fmt" "os/exec" ) func main() { app := "echo" arg0 := "-e" arg1 := "Hello world" arg2 := "\n\tfrom" arg3 := "golang" cmd := exec.Command(app, arg0, arg1, arg2, arg3) stdout, err := cmd.Output() if err != nil { fmt.Println(err.Error()) return } // Print the output fmt.Println(string(stdout)) }
I hope this helps!
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