Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exec a shell command in Go

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?

like image 1000
Chris Bunch Avatar asked May 31 '11 02:05

Chris Bunch


People also ask

What is Golang exec?

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

What is OS exec?

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.

What is exec command?

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).


1 Answers

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!

like image 153
Lourenco Avatar answered Oct 10 '22 02:10

Lourenco