Essential Go  Edit on GitHub      File Issue

Parse command line arguments

Package flag in standard library is for parsing cmd-line arguments:

var (
	flgHelp bool
	flgEcho string
)

func parseCmdLineFlags() {
	flag.BoolVar(&flgHelp, "help", false, "if true, show help")
	flag.StringVar(&flgEcho, "echo", "", "")
	flag.Parse()
}

func main() {
	parseCmdLineFlags()
	if flgHelp {
		flag.Usage()
		os.Exit(0)
	}
	if flgEcho != "" {
		fmt.Printf("flag -echo: '%s'\n", flgEcho)
	}

	remainingArgs := flag.Args()
	for _, arg := range remainingArgs {
		fmt.Printf("Remainig arg: '%s'\n", arg)
	}
}
flag -echo: 'echo-arg'
Remainig arg: 'additional'
Remainig arg: 'arg'

Output above is a result of calling go run $file -echo echo-arg additional arg.

Defining arguments

Let’s say your program has an integer -retries option.

You register such option with flag package using:

var flgRetries int
defaultRetries := 0
usage := "retries specifies number of times to retry the operation"
flag.IntVar(&flgRetries, "retries", defaultRetries, usage)

There are functions for other common types:

If you register int argument with name retries, the way to provide it on cmd-line is -retries ${value} or -retries=${value}.

POSIX variant --retries or Windows variant /retries are not recognized.

For boolean values you can say: -help (implicitly true), -help=true or -help=false.

-help false is not a valid form for boolean variables.

Parsing and accessing remaining arguments

After parsing arguments, call flag.Parse().

Parsing fails if:

In case of failure, help text describing flags is shown and program exits with error code 2.

You can explicitly print help text using flag.Usage(). This is often triggered by -help flag.

Help text is based on usage text provided in flag.IntVar and others.

Command-line arguments that don’t start with - are untouched and can be accessed with flag.Args().

Limitations

Features missing from flag package:

If you need those features, your options are:

  ↑ ↓ to navigate     ↵ to select     Esc to close