Trying to execute the command to compile the Golang program, code:

var buildCommand = fmt.Sprintf("go build %s %s main.go", `-v -a -x`, `-ldflags="-w -s"`); var cmd = exec.Command(buildCommand) var err = cmd.Run() 

If I buildCommand variable buildCommand I will get:

go build -v -a -x -ldflags="-w -s" main.go

but when you run the program itself, the builder will issue: exec: "go build -v -a -x -ldflags=\"-w -s\" main.go , that is, add such signs "\ \" , and exec.Command itself exec.Command it adds, how can this be fixed?

  • Try to give a minimal working code that can be checked directly. - biosckon
  • You have the first error. You are exec.Command() incorrectly. The first argument should be the name of the command i. go and you give go build -v -a -x -ldflags="-w -s" main.go And further `` is the result of building a string for the error. View examples golang.org/pkg/os/exec/#Command - biosckon

1 answer 1

Probably you want something like this.

 package main import ( "fmt" "os" "os/exec" ) func main() { buildCommand := []string{"build", "-o", "new.exe", "-v", "-a", "-x", "-ldflags=-w -s", "main.go"} cmd := exec.Command("go", buildCommand...) out, err := cmd.CombinedOutput() if err != nil { fmt.Fprintf(os.Stderr, "%v\n%s\n", err, string(out)) } else { fmt.Printf("%s\n", string(out)) } } 

Try combining the boxes together for example instead of ... "-v", "-a" ... -> ... "-v -a" ... And try to understand the mistakes.

Good luck

  • Thank! Understand my mistake) - tramway