DEV Community

Cover image for Cobra Golang's CLI Library

Cobra Golang's CLI Library

Murad Bayoun on November 29, 2023

Introduction In Go (Golang), "cobra" is a popular and widely used command-line interface (CLI) library. Cobra provides a simple and eleg...
Collapse
 
wynandpieters profile image
Wynand Pieters

Really love the Cobra framework, been using it to build CLIs for years. One of the greatest features they've added in the last while is support for a completion command.

By running ./myapp completion --help you can see a list of available command, i.e.

Available Commands:
  bash        Generate the autocompletion script for bash
  fish        Generate the autocompletion script for fish
  powershell  Generate the autocompletion script for powershell
  zsh         Generate the autocompletion script for zsh
Enter fullscreen mode Exit fullscreen mode

And then running help for a specific one tells you how to load it into your shell of choice, e.g. ./myapp completion fish --help will give

Generate the autocompletion script for the fish shell.

To load completions in your current shell session:

    myapp completion fish | source

To load completions for every new session, execute once:

    myapp completion fish > ~/.config/fish/completions/myapp.fish

You will need to start a new shell for this setup to take effect.
Enter fullscreen mode Exit fullscreen mode

Et voila. Tab completion for your custom CLI. Awesome feature to just get out the box given how powerful the framework already is.