Cobra CLI

The following example program provides a working example of the Cobra CLI framework and its supporting file structure.

File Structure

Bash
cobracli/
├── cmd/
   ├── create.go
   ├── list.go
   └── root.go
├── go.mod
└── main.go

go.mod

Go
module cobracli

go 1.24

require github.com/spf13/cobra v1.9.0

main.go

Go
package main

import "cobracli/cmd"

func main() {
    cmd.Execute()
}

cmd/root.go

Go
package cmd

import (
    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "cobracli",
    Short: "A simple CLI example using Cobra",
    Long:  "cobracli is a sample command-line application demonstrating Cobra basics.",
}

// Execute is the entry point from main.go
func Execute() {
    cobra.CheckErr(rootCmd.Execute())
}

func init() {
    rootCmd.AddCommand(listCmd)
    rootCmd.AddCommand(createCmd)
}

cmd/list.go

Go
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var listCmd = &cobra.Command{
    Use:   "list",
    Short: "List available items",
    Run: func(cmd *cobra.Command, args []string) {
        items := []string{"item1", "item2", "item3"}
        fmt.Println("Available items:")
        for _, item := range items {
            fmt.Printf(" - %s\n", item)
        }
    },
}

cmd/create.go

Go
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var itemName string

var createCmd = &cobra.Command{
    Use:   "create",
    Short: "Simulate creating a new item",
    Run: func(cmd *cobra.Command, args []string) {
        if itemName == "" {
            fmt.Println("No item name provided. Use --name to specify one.")
            return
        }
        fmt.Printf("Dry-run: '%s' would be created here.\n", itemName)
    },
}

func init() {
    createCmd.Flags().StringVarP(&itemName, "name", "n", "", "Name of the item to create")
}

Build and run the cobracli example program with the following steps.

Bash
# create the files listed above in the correct directory structure
go mod init cobracli
go: creating new go.mod: module cobracli
go: to add module requirements and sums:
	go mod tidy
go mod tidy
go: finding module for package github.com/spf13/cobra
go: found github.com/spf13/cobra in github.com/spf13/cobra v1.9.1
go build -o cobracli
./cobracli
cobracli is a sample command-line application demonstrating Cobra basics.

Usage:
  cobracli [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  create      Simulate creating a new item
  help        Help about any command
  list        List available items

Flags:
  -h, --help   help for cobracli

Use "cobracli [command] --help" for more information about a command.
./cobracli list
Available items:
 - item1
 - item2
 - item3
./cobracli create
No item name provided. Use --name to specify one.
./cobracli create --name myitem
Dry-run: 'myitem' would be created here.