Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error message from exec command

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?

like image 643
Madhuka Wickramapala Avatar asked Dec 14 '18 11:12

Madhuka Wickramapala


1 Answers

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())
}
like image 145
KibGzr Avatar answered Oct 24 '22 01:10

KibGzr