Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

Building CLIs With flag, os.Getenv, and Exit Codes

Parse command-line flags, fall back to environment variables, write errors to stderr, and return testable exit codes. After this, your Go CLIs behave cleanly in scripts and containers.

Course content

Sign in to save your progress.

Course Home

Command-line tools and containerized services share the same operational contract: they accept settings from flags and environment variables, send real data to os.Stdout, send errors to os.Stderr, and communicate success or failure back to bash, Docker, or CI with an integer exit code.

Skip ahead

If you already keep main() down to os.Exit(run(os.Args[1:])), parse flags with flag.NewFlagSet, default to os.Getenv, and write errors to os.Stderr, take the section quiz to wrap up Go for Beginners.

Experiment 1: Why calling os.Exit(1) inside helpers breaks cleanup and tests

When a helper function hits a bad flag or missing file, calling os.Exit(1) (or log.Fatal, which calls os.Exit(1)) terminates the OS process immediately—skipping every deferred cleanup and killing the entire go test runner if you try to test it! Instead, return an integer exit code from a run() function so every defer executes cleanly before main() exits:

package main

import "fmt"

func run() int {
	defer fmt.Println("cleanup ran!")
	return 1
}

func main() {
	code := run()
	fmt.Println("would exit with:", code)
}
cleanup ran!
would exit with: 1

In a real binary, main() is simply os.Exit(run(os.Args[1:])). All flag parsing, file closing, and cleanup defers finish inside run before os.Exit terminates the process.

Experiment 2: Flags overriding environment variables with flag.NewFlagSet

In Docker and Kubernetes, configuration usually arrives via environment variables (PORT=9090), while local developers often override it with a CLI flag (-port 8080). Using flag.NewFlagSet with os.Getenv("PORT") as the default supports both—and avoids mutating the global flag.CommandLine state so unit tests can invoke run(...) repeatedly:

package main

import (
	"flag"
	"fmt"
	"os"
)

func run(args []string) int {
	fs := flag.NewFlagSet("portcheck", flag.ContinueOnError)
	port := fs.String("port", os.Getenv("PORT"), "listen port")
	if err := fs.Parse(args); err != nil {
		return 2
	}
	if *port == "" {
		fmt.Fprintln(os.Stderr, "error: -port or PORT is required")
		return 1
	}
	fmt.Printf("listening on :%s\n", *port)
	return 0
}

func main() {
	fmt.Println("missing:", run(nil))
	os.Setenv("PORT", "9090")
	fmt.Println("from_env:", run(nil))
	fmt.Println("from_flag:", run([]string{"-port", "8080"}))
}
error: -port or PORT is required
missing: 1
listening on :9090
from_env: 0
listening on :8080
from_flag: 0

Experiment 3: Why os.Stderr keeps shell pipes working

Suppose someone pipes your CLI's JSON output into jq: ./portcheck | jq .. If your tool prints "error: -port is required" using fmt.Println(...) (which writes to os.Stdout), jq tries to parse that error sentence as JSON and fails cryptically! Writing errors with fmt.Fprintln(os.Stderr, ...) sends diagnostics to the terminal while keeping os.Stdout strictly for structured output.

Experiment 4: Exit codes that scripts and containers expect

  • 0: Command succeeded cleanly.
  • 1: Runtime, config, or validation error (e.g., missing required PORT, failed HTTP check).
  • 2: Invalid CLI flag syntax or usage error (unknown flag, non-integer value for an int flag).

Common mistakes

  • Calling log.Fatal inside library or helper functions: Bypasses all defer statements and makes unit testing impossible. Return an error (or exit code from run) instead.
  • Putting flags after positional arguments: Go's standard flag package stops scanning flags at the first non-flag argument, so mycli input.csv -port 8080 ignores -port. Always place flags first.
  • Using global flag.String + flag.Parse() inside testable functions: Calling it twice in tests panics with flag redefined; always use flag.NewFlagSet.

💡 Tip

Pass stdout, stderr io.Writer into run(args []string, stdout, stderr io.Writer) int when you want unit tests to assert exact terminal output using bytes.Buffer—no OS process spawning needed.

What happens if you skip this step

CLIs that exit inside helpers or print errors to stdout skip file cleanups, break automated shell scripts and Docker healthchecks, and force slow end-to-end subprocess tests for simple flag checks.

You call defer tempFile.Close() at the top of a helper function, then call os.Exit(1) ten lines later on an error. Does tempFile.Close() run before the process exits?

About

Parse command-line flags, fall back to environment variables, write errors to stderr, and return testable exit codes. After this, your Go CLIs behave cleanly in scripts and containers.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.