Skip to content

CLI subcommand pattern

The CLI subcommand pattern is a design approach for command-line interfaces where a main executable acts as a dispatcher for more specific functions, often referred to as "subcommands." Instead of a utility accepting all arguments through a single set of flags, the executable interprets the first argument (e.g., get, add) to determine which specific operation to execute^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

Structure

Implementing this pattern typically involves three main architectural components^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]:

  1. Flag Definition: Creating a dedicated FlagSet for each subcommand to define its specific arguments and options. For example, getCmd := flag.NewFlagSet("get", flag.ExitOnError) creates a parser specifically for the get operation^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
  2. Routing: Using a control flow statement (like a switch statement) to inspect the primary argument (e.g., os.Args[1]) and direct execution to the appropriate handler function^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
  3. Parsing: Specifically parsing the argument list slice starting from the index after the subcommand (e.g., os.Args[2:]) so that the subcommand's flag parser only sees its relevant flags^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

Input Handling

A key aspect of this pattern is the validation of input at the subcommand level^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]. This involves checking that required flags are present and valid. For example:

  • get command: Validates that either an --id is provided or the --all flag is set to retrieve the full list^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].
  • add command: Validates that multiple fields—such as ID, title, URL, and description—are present before constructing the data object to be saved^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md].

Sources

^[400-devops__09-Scripting-Language__golang__introduction__part-4.commandline__readme.md]