Search code examples
goflagsgo-cobra

How to use a flag with two different names (short and long)


I am using https://github.com/spf13/cobra to work with flags.

I want my CLI to have flag with two names: -t or --token.

I currently used it like that:

rootCmd.PersistentFlags().String("token", "", "Token to insert")  

But it prints me the flags like that:

Flags:

      -h, --help           help for myapp
          --token string   Token to insert  

I want it to be like that:

Flags:

      -h, --help           help for myapp
      -t, --token string   Token to insert   

How can I do it?
I didn't find it on google, I tried to search for multiple names for a flag but without success.


Solution

  • The answer is an example in the documentation. This example uses both --projectbase and -b:

    rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")