Home > Mobile >  Cannot run "git" with exec.Command()
Cannot run "git" with exec.Command()

Time:08-18

I want to run exec.Command("git", "config", "--global", "user.name") and read the output.

On windows the word "git" translates to the git path (C:\Program Files\...\git.exe). Then it tries to run C:\Program (which is not a path to an executable).

I have tried escaping the space, I have tried to add parentheses around the path, or only around the space and escape them. Nothing worked.

arg0 := "config"
arg1 := "--global"
arg2 := "\"user.name\""
bcmd := exec.Command("git", arg0, arg1, arg2)
var stdout bytes.Buffer
bcmd.Stdout = &stdout
err := bcmd.Run() 

I have tried adding parentheses and it did not help.

CodePudding user response:

You should not use quotes for arg2. As for reading the output it depends what you understand by reading. The output will be written to the buffer which is stdout in your case. You can obtain the bytes of the output using stdout.Bytes() and if you want the actual string (which I assume you actually want) you can just cast to string using string(stdout.Bytes()).

package main

import (
    "bytes"
    "fmt"
    "log"
    "os/exec"
)

func main() {
    bcmd := exec.Command("git", "config", "--global", "user.name")
    var stdout bytes.Buffer
    bcmd.Stdout = &stdout
    err := bcmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf(string(stdout.Bytes()))
}

There also is another simpler way to do the same thing using Output().

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    outputBytes, err := exec.Command("git", "config", "--global", "user.name").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf(string(outputBytes))
}

Both will print your git username.

  • Related