Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 147 ยท Standard Library

Command-Line Programs: flag and os.Args

Build command-line tools in Go with os.Args and the flag package - typed flags, usage text, custom flag types, subcommands with FlagSet, exit codes and environment variables, testable in the editor.

Go is a favorite language for command-line tools: it compiles to a single static binary that you can copy anywhere. Almost every such tool needs to read arguments (mytool --verbose --count 3 file.txt), print help, report errors with an exit code and sometimes read environment variables. The standard library covers all of that with os.Args, the flag package, os.Exit and os.Getenv.

In our editor the program starts without arguments, so the examples simulate a command line: instead of the global flags, they create a flag.FlagSet and call Parse on a slice you choose. That's also exactly how you make a CLI testable in real projects.

os.Args: the raw arguments

os.Args is a []string. Element 0 is the program's path and the real arguments start at index 1. It does no parsing at all: a quoted argument like "hello world" arrives as one element after the shell has processed it.

Go Reading os.Args

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For a tool with one required argument os.Args is enough. Once you want options with names, defaults, types and help text, use flag.

The flag package

Declare flags, call flag.Parse(), then read the values. Each constructor returns a pointer to the value (flag.Int returns *int); the Var forms such as flag.IntVar store into a variable you already have.

A real program looks like this (shown read-only because the editor passes no arguments):

Go
package main

import (
	"flag"
	"fmt"
)

func main() {
	name := flag.String("name", "world", "who to greet")
	count := flag.Int("count", 1, "how many times")
	loud := flag.Bool("loud", false, "use upper case")
	flag.Parse()

	fmt.Println(*name, *count, *loud, flag.Args())
}
Terminal
go run main.go -name Ada -count 2 -loud extra1 extra2

flag.Parse() reads os.Args[1:]. Both -name Ada and --name=Ada are accepted (one or two dashes make no difference), and for booleans the bare -loud means true. Parsing stops at the first non-flag argument, or after --; whatever is left is available as flag.Args(), flag.NArg() and flag.Arg(i). That is why options must come before positional arguments.

Testing with a FlagSet

A flag.FlagSet is an independent set of flags. flag.CommandLine, used by the top-level functions, is just one of them. By creating your own and passing an explicit slice, you can run the whole parser inside a function:

Go Typed flags on a FlagSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note the last argument in the first call: after a.txt, parsing stopped, so -notflag is a plain positional argument. -timeout 1m30s was converted by flag.Duration, which uses time.ParseDuration syntax.

Errors, help and usage

When a flag is unknown or a value can't be converted, Parse reports it according to the set's error handling mode:

  • flag.ExitOnError: print the error and usage, then exit (status 2). This is the default for the global flag.Parse().
  • flag.ContinueOnError: return the error to you.
  • flag.PanicOnError: panic.

Passing -h or -help prints the usage and returns flag.ErrHelp, which is not a failure and should usually lead to exit status 0. You can replace the usage text by assigning to fs.Usage:

Go Errors and custom usage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

PrintDefaults writes each flag with its type, default and description, which is why good descriptions matter. The error text for the bad width comes from strconv: invalid value "wide" for flag -width: parse error.

Exit codes and structuring main

By convention, exit status 0 means success, 1 a runtime failure, and 2 a usage error (the one flag uses). Calling os.Exit skips deferred functions, so the clean pattern is to keep main tiny:

Go
func main() {
	os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}

func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
	// parse flags, do the work, return an exit code
	return 0
}

All the logic lives in run, which takes its inputs and outputs as parameters. You can then call it from a test, or from a lesson like this one, with fake arguments and a bytes.Buffer, and defer works normally inside it.

Normal results go to stdout and diagnostics to stderr, so that mytool > out.txt keeps errors on the screen and pipelines see only data.

Custom flag types

Any type that implements flag.Value (two methods: String() string and Set(string) error) can be a flag. The usual use is a flag that can be repeated, such as -tag a -tag b. For one-off cases flag.Func takes a callback:

Go flag.Value and flag.Func

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

flag.Func appeared in Go 1.16 and BoolFunc in Go 1.21. The Set method may be called several times, which is what makes repeatable flags work.

Subcommands

Tools like git commit or go build have subcommands, each with its own flags. The flag package has no direct support, but a FlagSet per subcommand is the standard approach: look at the first argument to choose the set, then parse the rest with it.

Go Subcommands with FlagSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Each subcommand sees only its own flags, so list -priority 2 would be rejected as unknown, which is exactly what you want.

Environment variables

Environment variables are the usual way to pass secrets and deployment settings. os.Getenv(key) returns an empty string when the variable is unset; os.LookupEnv also tells you whether it was set. A common design is flag > environment variable > default, by using the environment value as the flag's default:

Go Environment variables as defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Beyond the standard library

The flag package is deliberately small: it has no short and long names for one option (-v and --verbose), no automatic subcommand help and no shell completion. Popular third-party libraries such as cobra (used by kubectl and the GitHub CLI) and urfave/cli add those features, and for many tools flag is still enough. Learn it first; you'll see exactly what the bigger libraries build on.

Flags before positional arguments only: tool -v file.txt works, but tool file.txt -v treats -v as a file name. Most Go tools document this explicitly, and it is one reason libraries like cobra are popular.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is os.Args[0]?

    os.Args[0] is the program itself; the user's arguments start at index 1.
  2. 2. What does flag.Int("count", 1, "how many") return?

    The constructors return pointers. Read the value with *count after calling Parse.
  3. 3. For tool -v file.txt -x, which arguments does flag.Args() return?

    Parsing stops at the first non-flag argument (file.txt), so everything from there on, including -x, is positional.
  4. 4. Which ErrorHandling mode returns parse errors to your code instead of exiting?

    ContinueOnError makes Parse return the error. ExitOnError, the default for the global flags, exits with status 2.
  5. 5. Why put the program logic in a run(args, ...) int function called from main?

    os.Exit skips deferred functions. A run function returns the exit code, so cleanup works and tests can call it directly.

Summary

  • os.Args holds the raw arguments; index 0 is the program, real arguments start at 1.
  • flag provides typed flags (String, Int, Bool, Duration, Float64, ...) that return pointers, or ...Var forms that fill your own variables; call Parse, then use Args, NArg and Arg.
  • Flags must come before positional arguments; -x and --x, and -x=v and -x v, are equivalent.
  • Use your own flag.NewFlagSet with ContinueOnError to test parsing, customize Usage and build subcommands.
  • Custom types implement flag.Value; flag.Func and flag.BoolFunc cover quick cases.
  • Return exit codes from a run function: 0 success, 1 failure, 2 usage error; send data to stdout and diagnostics to stderr.
  • os.LookupEnv reads environment variables; using them as flag defaults gives flag > environment > default.

Next: Hashing and Cryptography covers digests, random bytes and encryption.