Getting Started with Cobra: Creating Multi-Level Command Line Interfaces in Golang
Tags: go, cli, cobra
Published: 2023-07-31 10:29:40

---
title: Getting Started with Cobra: Creating Multi-Level Command Line Interfaces in Golang
published: true
description: The article delves into the step-by-step process of building a CLI application using Cobra, demonstrating how to structure commands with different levels of hierarchy, and how to organize complex functionalities into nested commands. Readers will gain a comprehensive understanding of how to harness Cobra's capabilities to design robust, deeply nested CLIs, enabling them to create command-line tools that are both intuitive and efficient for end-users.
tags: golang, go, cli, cobra
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/peg8amigr3g8bf2mbh99.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-07-31 09:54 +0000
series: Getting Started with Cobra - Creating Multi-Level Command Line Interfaces in Golang
---

Introduction:
------------------
Creating a CLI using Cobra in Golang is a great choice, and nesting commands can help organize and structure your CLI effectively. Below, I'll guide you through the process of creating a nested CLI using Cobra.

What is Cobra?
------------------
Cobra is a robust and flexible Golang library for building CLI applications. It provides an elegant and easy-to-use interface to define commands, flags, and arguments, making it a popular choice among Golang developers for creating CLI applications.

Prerequisites:
------------------
Before we begin, ensure you have Go (Golang) installed and have set up your workspace properly. You can install Cobra by executing the following command:

```bash
go get -u github.com/spf13/cobra@latest
```

Getting Started:
------------------
Let's start by creating a new Golang project in your desired workspace. Once your project is set up, we'll initialize a Cobra application by running the following command:

```bash
cobra init [your-cli-app-name]
```

This will create a basic structure for your CLI application, including the necessary files and folders.

Defining the Root Command:
------------------
The root command is the entry point of your CLI application. It is the command executed when users run your application without any subcommands. Open the `cmd/root.go` file, and let's define the root command using Cobra:

```go
// cmd/root.go
package cmd

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

var rootCmd = &cobra.Command{
	Use:   "[your-cli-app-name]",
	Short: "A brief description of your CLI application",
	Long: `A longer description that explains your CLI application
in detail. For example, you can mention the various commands
available and what they do.`,
	Run: func(cmd *cobra.Command, args []string) {
		// This function will be executed when the root command is called
		fmt.Println("Welcome to [your-cli-app-name]! Use --help for usage.")
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
```

You can try to run it:
```
$ go run main.go                                                          
> Welcome to [your-cli-app-name]! Use --help for usage.
```

Adding a Nested Command:
------------------
Next, let's add a nested command to our CLI application. Nested commands are subcommands that provide additional functionality under the main command. For example, let's create a subcommand called "subcommand" for our application. Open the `cmd/subcommand.go` file and define the nested command:

```go
// cmd/subcommand.go
package cmd

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

var subCmd = &cobra.Command{
	Use:   "subcommand",
	Short: "A brief description of the subcommand",
	Long: `A longer description that explains the subcommand
in detail. For example, you can mention how it complements
the main command and what options it supports.`,
	Run: func(cmd *cobra.Command, args []string) {
		// This function will be executed when the "subcommand" is called
		fmt.Println("Running the subcommand!")
	},
}

func init() {
	rootCmd.AddCommand(subCmd)
}
```

Lets try it again:
```
$ go run main.go subcommand           
> Running the subcommand!
```

Conclusion:
------------------
Congratulations! 🎉 You have successfully created a CLI application using Cobra with a nested command. You can continue to expand your application by adding more subcommands, flags, and arguments to meet your specific needs.

In this blog post, we've only scratched the surface of what you can achieve with Cobra. It's a powerful library that allows you to create professional-grade CLIs with ease. Experiment with various options, customize your commands, and explore more features provided by Cobra.

Happy coding! 👨‍💻

Footnote:
------------------
Full code is available on [github](https://github.com/frasnym/basic-cobra-cli) 🤝