Command-Line Subcommands in Go

Go: Command-Line Subcommands

Go provides a way to implement command-line subcommands using the flag package and the os package. Here's an example of how to implement subcommands in Go:

Command-Line Subcommands example in Go

    package main

    import (

    func main() {
        // Define a subcommand "greet"
        greetCmd := flag.NewFlagSet("greet", flag.ExitOnError)
        greetName := greetCmd.String("name", "", "the name to greet")

        // Parse the command-line arguments to determine which subcommand to run
        if len(os.Args) < 2 {
            fmt.Println("Please specify a subcommand")
        switch os.Args[1] {
        case "greet":
            fmt.Printf("Unknown subcommand: %s\n", os.Args[1])

        // Run the selected subcommand
        if greetCmd.Parsed() {
            if *greetName == "" {
                fmt.Println("Please provide a name to greet using the -name flag")
            fmt.Printf("Hello, %s!\n", *greetName)

This code defines a subcommand greet using the flag.NewFlagSet function, which creates a new flag set with a specified name and error handling behavior. The subcommand has a single flag -name to specify the name to greet.

The code then parses the command-line arguments to determine which subcommand to run. If no subcommand is specified, the program prints an error message and exits. If the greet subcommand is specified, the code parses the remaining arguments using the greetCmd.Parse function.

Finally, the code runs the selected subcommand, in this case, the greet subcommand. If the greetName flag is not provided, the program prints an error message and exits. Otherwise, it uses the value of the flag as the name and prints a personalized greeting.

You can add more subcommands by defining additional flag sets and adding more cases to the switch statement.

I hope that helps you get started with working with command-line subcommands in Go! Let me know if you have any more questions

Previous Article