Go Flag Package: Build Command Line Tools

Updated 4 min read
Go Flag Package featured image: cards for string flags, number flags and help text

The Go flag package turns a plain program into a command line tool with options and a help screen. In this post, you will define flags, read extra arguments, write a custom help message and add subcommands. Each idea comes with a short example.

In the last lesson, Go environment variables for configuration set options from outside the program. Flags do the same job, but per run. We also use pointers a lot here, so pointers in Go is a quick refresher.

What Is the Go Flag Package?

A command line flag is an option you type after the program name, such as -n 3 or -loud. The standard flag package reads those options, converts them to the right type and prints help when something is wrong.

Think of ordering coffee. The drink is always coffee, but you add options: large, oat milk, extra shot. Flags are those options for your program.

Defining Flags with the Go Flag Package

name := flag.String("name", "World", "who to greet")
times := flag.Int("n", 1, "how many times to greet")
loud := flag.Bool("loud", false, "print in capital letters")
flag.Parse()

msg := "Hello, " + *name + "!"
if *loud {
	msg = strings.ToUpper(msg)
}
for i := 0; i < *times; i++ {
	fmt.Println(msg)
}

Each function takes a name, a default value and a help text. It returns a pointer, so you read the value with *name. Most importantly, call flag.Parse() before reading any flag.

$ go build -o greet .
$ ./greet
Hello, World!
$ ./greet -name=Asha -n 2 -loud
HELLO, ASHA!
HELLO, ASHA!

The diagram below shows how the Go flag package splits a command into flags and leftover arguments.

Go Flag Package diagram showing a command split into flags and leftover arguments by flag.Parse

flag.Parse reads each option into its variable, and everything after the flags stays in flag.Args.

Flag Syntax the Go Flag Package Accepts

You typeWorks?
-name=AshaYes
-name AshaYes, except for bool flags
--name AshaYes, two dashes also work
-loudYes, sets a bool to true
-loud=falseYes, the only way to set a bool to false

Reading Extra Arguments

$ ./greet --name Ravi go is fun
Hello, Ravi!
extra args: [go is fun] 3

After parsing, flag.Args() returns the words that were not flags, and flag.NArg() counts them. However, parsing stops at the first non-flag word. So ./greet go -name=Asha treats -name=Asha as a plain argument.

Flags Bound to Variables

var wait time.Duration
flag.DurationVar(&wait, "wait", 0, "pause between greetings")

The Var versions write into a variable you already have. In addition, flag.Duration understands values like 500ms or 2s for you.

Custom Help Text

flag.Usage = func() {
	fmt.Fprintf(os.Stderr, "Usage: greet [flags] [extra words]\n")
	flag.PrintDefaults()
}
$ ./greet -h
Usage: greet [flags] [extra words]
  -loud
    	print in capital letters
  -n int
    	how many times to greet (default 1)
  -name string
    	who to greet (default "World")

Running with -h prints this help for free, and the program then exits with status 0. Without a custom Usage, Go prints a shorter title based on the program name. So a custom message is worth a few lines, because it tells users what the extra words mean. Notice that the Go flag package also shows each type and default value.

Subcommands with FlagSet

switch os.Args[1] {
case "add":
	addCmd := flag.NewFlagSet("add", flag.ExitOnError)
	title := addCmd.String("title", "", "task title")
	addCmd.Parse(os.Args[2:])
	fmt.Println("adding task:", *title)
case "list":
	listCmd := flag.NewFlagSet("list", flag.ExitOnError)
	done := listCmd.Bool("done", false, "show finished tasks")
	listCmd.Parse(os.Args[2:])
	fmt.Println("listing tasks, done =", *done)
}
$ ./tasks add -title "Learn flags"
adding task: Learn flags
$ ./tasks list -done
listing tasks, done = true

Tools like git and go use subcommands. Each FlagSet holds its own flags, so add and list never clash.

Common Mistakes with the Go Flag Package

Error you seeWhy it happensHow to fix it
flag provided but not defined: -xThe user typed an unknown flag.Check the spelling, or run with -h.
invalid value “abc” for flag -n: parse errorText was given to an int flag.Pass a number.
flag needs an argument: -nameThe flag had no value.Write -name=Asha.
Flags always show defaultsflag.Parse() was never called.Call it before reading flags.

On these errors the program prints the help and exits with status 2. Command line questions also appear in interviews, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • The Go flag package parses command line options into typed values.
  • Each flag function returns a pointer, so read it with *.
  • Always call flag.Parse() before using flags.
  • flag.Args() holds the leftover words after the flags.
  • Use flag.NewFlagSet to build subcommands.

What’s Next?

You can now build handy command line tools. Next, we will find out where a program spends its time and memory with profiling and pprof.

Next lesson: Go Profiling with pprof for Beginners