7
votes

I am using Go to create a CLI. I am executing a command and if there is an error thrown from the OS I want to print it.

cmd := exec.Command("abc", "run", pathToFile)
err := cmd.Start()
if err != nil {
    fmt.Printf("Error : %v \n", err)
    os.Exit(1)
}
err = cmd.Wait()
if err != nil {
    fmt.Printf("Error: %v \n", err)
    os.Exit(1)
}

This only gives me the exit status code

Error:  exit status 1 

This is not descriptive enough.

When I run the command directly in terminal I get the error message clearly.

source does not exist 'test.exe'

Is there a way to print the message?

1

1 Answers

10
votes

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

cmd := exec.Command("abc", "run", pathToFile)
stderr, _ := cmd.StderrPipe()
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}