How to Exit a Go Program with an Exit Code
Every program ends with an exit code: 0 when it succeeded, anything else when it didn't. A Go program sets its own with os.Exit. There's one surprise on the way: go run doesn't pass that code on, so you only see the real number from the built program.
Syntax
os.Exit(<code>)
| Part | What it does |
|---|---|
os.Exit | Ends the program immediately. |
<code> | The exit code: 0 for success, a non-zero number for an error. |
The os documentation: "Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run." It adds: "For portability, the status code should be in the range [0, 125]."
The Example
The example checks whether all orders are paid. They aren't, so it prints an error and exits with code 2. Running it with go run and as a built program shows the difference.
Prerequisites
- Go. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import (
"fmt"
"os"
)
func main() {
allPaid := false
if !allPaid {
fmt.Fprintln(os.Stderr, "Some orders are not paid.")
os.Exit(2)
}
fmt.Println("All orders are paid.")
}
Step 2: Run It with go run, Then as a Built Program
- macOS / Linux
- Windows (PowerShell)
go run main.go
echo $?
go build -o orders main.go
./orders
echo $?
Some orders are not paid.
exit status 2
1
Some orders are not paid.
2

go run main.go
$LASTEXITCODE
go build -o orders.exe main.go
.\orders.exe
$LASTEXITCODE
Some orders are not paid.
exit status 2
1
Some orders are not paid.
2

exit status 2 is printed by go run, which noticed the program's code, but go run itself then exited with 1. The built program reported its real code, 2. go help run says so in one line: "The exit status of Run is not the exit status of the compiled binary."
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Checking the exit code of go run | It's 1 whatever code the program used | Build the program and check its code |
Relying on defer to clean up before os.Exit | Deferred functions don't run | Clean up before calling os.Exit |
Calling os.Exit deep inside the code | Callers can't react or clean up | Return an error and call os.Exit only in main |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A script always sees 1, never your code | It runs the program through go run | Run the built program |
A deferred message never prints | os.Exit skipped it | Move the cleanup before os.Exit |
FAQ
What code does a Go program end with when main returns normally?
0.
What does a panic give?
A non-zero code. An unrecovered panic, such as a nil pointer dereference, ended a test program with code 2.
Conclusion
os.Exit(code) ends a Go program with that code, skipping deferred functions. go run always reports 1 for a failure, so build the program when the exact code matters, as scripts and CI jobs do.
