liveBook · Manning

UNIX-style flag processing

As explained in Go in Practice, Second Edition

UNIX-style flag processing is command-line option parsing that follows conventions common to UNIX, Linux, and BSD tools, including short and long options.

UNIX-style flag processing parses command-line options using conventions familiar from Linux- and BSD-based tools, including short flags that can be combined, such as ls -la. Go’s built-in flag package provides basics but may not match these interaction expectations. section 2.1.4

A pragmatic implementation strategy is to:

  • Use an existing command-line library rather than maintaining a project-specific fork of Go’s flag package. section 2.1.4
  • Define long and short aliases, defaults, help text, required flags, commands, and subcommands through the library interface. section 2.1.4
  • Use built-in flag and parser tooling when an advanced case only needs to recognize known tokens from a single argument. section 2.1.4
Listing 2.6 Running Hello World in CLI with flags
$ hello_cli
Hello World!
$ hello_cli --name Inigo
Hello Inigo!
$ hello_cli –n Inigo
Hello Inigo!
$ hello_cli –help
NAME:
   hello_cli - Print hello world
USAGE:
   hello_cli [global options] command [command options] [arguments...]
VERSION:
   0.0.0
COMMANDS:
   help, h   Shows a list of commands or help for one command
GLOBAL OPTIONS:
   --name, -n 'World'      Who to say hello to.
   --help, -h              show help
   --version, -v           print the version

A runnable CLI interaction demonstrates long and short name flags, help output, defaults, and command metadata. section 2.1.4

How Go in Practice, Second Edition covers it

How deep it goes
Compares standard-library limitations with library-based implementation and briefly notes token parsing, stopping short of parser internals.
Examples
Uses hello_cli interactions, combined ls flags, Cobra flag declarations, and a subcommand-based calculator.
What it assumes
Assumes basic Go command-line programming and introduces library-based flag handling as an alternative to the standard package.
What you can do after
Builds Go command-line tools with familiar short and long options by adopting an existing command-line library.
How it connects
Connects command-line applications with Go’s flag package, Cobra, commands, subcommands, and argument parsing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.