Exit Code

The following example program demonstrates how to properly use exit codes in a CLI application. It shows both returning numeric exit codes to the operating system (which are essential for scripting, automation, and cron jobs) and printing meaningful messages to the console.

Go
package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ./exitcode <code>")
		os.Exit(1) // Standard error for usage issues
	}

	code, err := strconv.Atoi(os.Args[1])
	if err != nil {
		fmt.Printf("Invalid exit code provided: %s\n", os.Args[1])
		os.Exit(2) // Error converting input to integer
	}

	message := getExitMessage(code)
	fmt.Printf("Exited with code %d - %s\n", code, message)

	os.Exit(code)
}

func getExitMessage(code int) string {
	switch code {
	case 0:
		return "Exited Successfully"
	case 1:
		return "General Error"
	case 2:
		return "Misuse of Shell Command"
	case 126:
		return "Command Invoked Cannot Execute"
	case 127:
		return "Command Not Found"
	case 130:
		return "Program Terminated by Control-C"
	default:
		return "Unknown Exit Code"
	}
}
Expand

Copy the code above, and follow these steps to build and run it in a Linux environment:

Bash
mkdir ~/build/exitcode
cd ~/build/exitcode
vim main.go
go mod init exitcode
go: creating new go.mod: module exitcode
go: to add module requirements and sums:
	go mod tidy
go mod tidy
go build -o exitcode

The program can be used to demonstrate common exit codes:

Bash
./exitcode
Usage: ./exitcode <code>

./exitcode 0
Exited with code 0 - Exited Successfully

./exitcode 127
Exited with code 127 - Command Not Found

./exitcode 130
Exited with code 130 - Program Terminated by Control-C

How do you confirm this works using standard Unix conventions?
After executing the command with a specific exit code, use the echo $? command to display and verify the returned exit code.

Bash
./exitcode 130
Exited with code 130 - Program Terminated by Control-C
echo $?
130

In PowerShell Write-Host would be used to confirm the exit code.

PowerShell
.\exitcode.exe 0
Write-Host $LASTEXITCODE
0

.\exitcode.exe 2
Write-Host $LASTEXITCODE
2

Here is a table of common exit codes:

Exit CodeMeaning
0Success
1General error
2Misuse of shell command
126Command invoked cannot execute
127Command not found
130Script terminated by Ctrl-C (SIGINT)