Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is Cobra?

Sarvech Qadir

Cobra is a powerful library and tool in Golang used to create CLI (Command-Line Interface) applications. Cobra does this by providing tools that automate the process and provide key abstractions that increase developer productivity.

svg viewer

Why use Cobra?

Among the many benefits of using Cobra, here are some to consider:

  • Easy to create subcommand-based CLIs and use nested subcommands.
  • Automatic help generation for commands and flags.
  • Increased productivity because of commands such as cobra init appname & cobra add cmdname.
  • Helpful, intelligent suggestions (app srver… did you mean app server?).


To use Cobra, you need to use go get to install the library’s latest version. This command will install the cobra generator executable along with the library and its dependencies:

go get

Next, include Cobra in your application:

import ""

Using cobra

Initialize your Cobra CLI app with the cobra init --pkg-name <app> command. This command will construct the basic application structure for you.

You can add commands to your application with the cobra add <commandName> syntax.

Cobra warns against the use of snake_case/snake-case because it may lead to errors. Instead, use camelCase.


In order to use Cobra, a user must define a structure with a name, description, and function to run the logic. Look at code below:

cmd := &cobra.Command{
        // cobra name
	Run:   Hello,
        // identifier
	Use:   `hello`,
	Short: "GreetUser",
        // what this command should print
	Long:  "This command will print Hello World",

This design is quite similar to the native Go commands (like go env, go fmt, etc.) in the standard library.

For further understanding of how to use cobra, click here.




Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring