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 \"f
This answer does not represent the current state of the Go standard library. Please take a look at @Lourenco's answer for an up-to-date method!
Your example does not actually read the data from stdout. This works for me.
package main
import (
"fmt"
"exec"
"os"
"bytes"
"io"
)
func main() {
app := "/bin/ls"
cmd, err := exec.Run(app, []string{app, "-l"}, nil, "", exec.DevNull, exec.Pipe, exec.Pipe)
if (err != nil) {
fmt.Fprintln(os.Stderr, err.String())
return
}
var b bytes.Buffer
io.Copy(&b, cmd.Stdout)
fmt.Println(b.String())
cmd.Close()
}