Home > Software engineering >  Record exit code from command
Record exit code from command

Time:01-01

I am trying to run a command within go with the following lines of code.

    cmd := exec.Command(shell, `-c`, unsliced_string) 
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin
    cmd.Run()

the variable shell is gathered from os.Getenv("$SHELL") and variable unsliced_string is the args fed from the command line.

I need the status/error code from the command after it runs.

So if the command being run (from the command) is exit 100, i need a variable saved which retains the error status code, in this case 100

Overall, i need a variable which records the error code of the command run

I have tried using .Error() however it has exit status 100 instead of just 100 As a last resort I can just use strings.Replaceall or strings.Trim

CodePudding user response:

Sure, there are two ways:

cmd := exec.Command(shell, `-c`, unsliced_string) 
err := cmd.Run()
if exitErr, ok := err.(*exec.ExitError); ok {
    exitCode := exitErr.ExitCode()
    fmt.Println(exitCode)
} else if err != nil {
    // another type of error occurred, should handle it here
    // eg: if $SHELL doesn't point to an executable, etc...
}
cmd := exec.Command(shell, `-c`, unsliced_string) 
_ := cmd.Run()
exitCode := cmd.ProcessState.ExitCode()
fmt.Println(exitCode)

I would highly recommend using the first option, that way you can catch all exec.ExitError's and handle them how you want. Also cmd.ProcessState is not populated if the command has not exited or if the underlying command is never run due to another error, so safer to use the first option.

  •  Tags:  
  • go
  • Related