os.Exit function immediately terminates your program with a specific exit status code. This is important for shell scripts and other programs that check the success or failure of commands.
Basic Usage
Exit Status Codes
Exit codes communicate program results to the shell:0 - Success
The program completed successfully without errors
1 - General Error
A general error occurred (most common error code)
2 - Misuse
Typically indicates invalid command-line arguments
Custom Codes
Use codes 3-255 for application-specific errors
Checking Exit Status
Using go run
When you usego run, Go intercepts the exit status:
Using a compiled binary
With a compiled binary, you can check the exit code directly:$? shell variable contains the exit status of the last command.
Exit vs Return from main
In Go, returning from
main always results in exit code 0. Unlike C, Go does not support returning an integer from main to indicate exit status. If you need a non-zero exit code, you must use os.Exit.Common Patterns
Error Exit Helper
Create a helper function for error exits:Multiple Exit Codes
Use different codes for different error types:Cleanup Before Exit
Since defers don’t run, you need explicit cleanup:Example Output
! from the deferred fmt.Println never appears.
When to Use os.Exit
Use os.Exit when...
Use os.Exit when...
- You need to signal specific error conditions to shell scripts
- Building CLI tools that follow Unix conventions
- You need immediate termination without cleanup
- Implementing fail-fast behavior for critical errors
Avoid os.Exit when...
Avoid os.Exit when...
- You need to run deferred cleanup functions
- Writing library code (let callers decide how to handle errors)
- In the middle of complex operations that need unwinding
- Writing tests (use testing.T methods instead)
What about panic?
What about panic?
panic is different from os.Exit:panicunwinds the stack and runs deferspaniccan be recovered withrecover()os.Exitterminates immediately without unwindingos.Exitcannot be caught
panic for programming errors, os.Exit for controlled termination.Standard Exit Codes
While you can use any code from 0-255, following conventions helps:| Code | Meaning | Usage |
|---|---|---|
| 0 | Success | Program completed successfully |
| 1 | General error | Default error condition |
| 2 | Misuse | Invalid command-line arguments |
| 126 | Command can’t execute | Permission problem or not executable |
| 127 | Command not found | Path issue or typo |
| 128+n | Fatal error signal “n” | Program died due to signal n |
| 130 | Script terminated by Ctrl+C | SIGINT (signal 2) |
| 255 | Exit status out of range | Used when exit code exceeds valid range |
These conventions come from the Bash documentation and are widely followed in Unix-like systems.
Related Topics
Signals
Handle termination signals gracefully
Logging
Log errors before exiting