Command line flags
The flag package reads -name value pairs from the command line. Each flag is declared once, with a default and a help line, and returns a pointer that Parse fills; everything after the first non-flag argument is left for the program. A command with two subcommands usually has one set of flags per subcommand, which is the shape the capstone CLI project builds.
String, Int and Bool flags
The program declares three flags and reads them through the pointers after Parse. A string needs an argument, an int needs an integer and a bool can stand alone: -v means true. The command passes all three and two positional words, which the program prints as one slice.
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "world", "who to greet")
count := flag.Int("n", 1, "how many times")
verbose := flag.Bool("v", false, "print extra detail")
flag.Parse()
for i := 0; i < *count; i++ {
fmt.Printf("hello, %s\n", *name)
}
if *verbose {
fmt.Println("arguments:", flag.Args())
}
}
go build -o app main.go && ./app -name ada -n 2 -v extra1 extra2
hello, ada
hello, ada
arguments: [extra1 extra2]
The flags can come in any order before the first positional argument, and -name=ada is the same as -name ada. A flag after a positional argument is not parsed: it lands in flag.Args, which is why a command that accepts both puts its flags first or requires --.
A usage line
flag.Usage is the function that -h and a parse error call. The default prints the program name and every flag with its help; a custom one adds a line in the program's own syntax before the defaults. The output goes to standard error, and -h exits with status 0 because asking for help is not an error.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
port := flag.Int("port", 8080, "port to listen on")
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "usage: server [-port PORT]")
flag.PrintDefaults()
}
flag.Parse()
fmt.Println("listening on", *port)
}
go build -o app main.go && ./app -port 9090
./app -h ; echo "exit status: $?"
listening on 9090
usage: server [-port PORT]
-port int
port to listen on (default 8080)
exit status: 0
PrintDefaults sorts the flags and prints the type next to each name, then the help line indented on its own. A flag with a default value says so, and a string default is quoted; that is why the defaults are worth writing well, since they are the only documentation a user sees at the prompt.
An invalid value
A value that does not fit the flag's type is an error from Parse: the package prints the reason, calls the usage function and exits with status 2. The program never sees the bad value, so it cannot recover from it, which is the right behaviour for a command line: a typo should stop the program before it does anything.
./app -port abc ; echo "exit status: $?"
invalid value "abc" for flag -port: parse error
usage: server [-port PORT]
-port int
port to listen on (default 8080)
exit status: 2
The message names the value, the flag and the reason, and the usage follows on stderr. A negative port would parse and be wrong for a different reason, which is why a command checks its own ranges after Parse and prints its own message rather than relying on the package.
Positional arguments
flag.Args returns what is left after the flags and flag.NArg its length. The -- terminator ends flag parsing, which is how a program passes an argument that begins with a dash. The program below uppercases the positional words when asked.
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
upper := flag.Bool("upper", false, "print in upper case")
flag.Parse()
for _, arg := range flag.Args() {
if *upper {
arg = strings.ToUpper(arg)
}
fmt.Println(arg)
}
fmt.Println("count:", flag.NArg())
}
go build -o app main.go && ./app -upper -- one two
ONE
TWO
count: 2
Without the --, one and two would still be positional because they do not start with a dash; the terminator matters only for an argument such as -file that should be treated as a name. A command that takes one file usually checks NArg is 1 and prints the usage line otherwise.
Flags in a real command
A command with subcommands parses os.Args[1] as the subcommand name, then creates a flag.NewFlagSet for the rest. Each set has its own usage and its own exit behaviour, and a program that wants to return an error instead of exiting uses ContinueOnError and checks the result. The flag package has no long options and no combining of short ones, which is a deliberate limit of about a hundred lines of code; a program that needs more imports a library such as cobra.
Three rules keep a command line usable. Every flag gets a help line. The defaults work with no arguments at all. And an unknown flag is an error, not something to ignore, because a user who typed -nmae wants to know before the program does its work.
Exercises
- Add a duration flag with flag.Duration and pass -wait 1.5s. What does the help line print as the default?
- Move a flag after a positional argument and run the program. Where does the flag end up, and what does NArg report?
- Replace the usage function with one that returns an error from a FlagSet in ContinueOnError mode. Which error does Parse return for an unknown flag?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does flag.String return?
Answer
A pointer to the value that Parse fills
The pointer is dereferenced after Parse.
-
When are the flags parsed?
Answer
When flag.Parse is called
Before Parse the pointers hold the defaults.
-
What does a bool flag accept?
Answer
A bare -v, or -v=false
A bool flag is true when it appears alone.
-
Where does the usage output go?
Answer
Standard error
An error and a help request are diagnostics.
-
What exit status does -h produce?
Answer
0
Asking for help is not an error.
-
What does flag.Args return?
Answer
The arguments left after the flags
NArg is its length.
-
What does -- do on the command line?
Answer
Ends flag parsing
Everything after it is positional.
-
What happens with an invalid int value?
Answer
Parse prints the error and the usage, then exits 2
The default error handling exits.
-
What does flag.PrintDefaults print?
Answer
Each flag with its type, help and default
The list is sorted by flag name.
-
How does a command support subcommands?
Answer
One flag.NewFlagSet per subcommand
Each set has its own flags and usage.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev