os/exec.Cmd.Run appear to not redirect standard output of the process it runs

Viewed 41

I am writing an application in which I need to run certain external commands.

func Run(cmd string, args string, workingDirectory string) error {
    _cmd := exec.Command(cmd, strings.Split(args, " ")...)
    if len(workingDirectory) != 0 {
        _cmd.Dir = workingDirectory
    }
    var outb, errb bytes.Buffer
    _cmd.Stdout = &outb
    _cmd.Stderr = &errb
    err := _cmd.Run()
    if err != nil {
        return err
    }
    if errb.Len() > 0 {
        color.HEX("#ffef00").Println(errb.String())
    }
    if outb.Len() > 0 {
        color.Hex("#00ff5f").Println(outb.String())
    }
    return nil
}

When I test this method with Go or Git standard CLI commands, I encounter two issues:

1- The standard output is always empty 
2- The standard output is redirected to standard error 

for example:

Run("go", "mod tidy", "") 

This shows no output while when I run it against the same go.mod file directly in console, I can view the outputs.

another example:

Run("git", "clone [url]", "") 

All standard outputs are passed to standard error in this case.

What exactly is problem?

0 Answers
Related