8

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 Answer 1

16

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())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.