I looked for some similar problems but I couldn't find anything except this: https://github.com/spf13/cobra/issues/1025
My problem is about inserting some string which contains a dash at the beginning like the following example,
go run myapp exampleCmd set "-Dexample"
Cobra seems to take the input -Dexample as internal parameter because returns this output:
Error: unknown shorthand flag: 'D' in -Dexample
Usage:
myapp exampleCmd set [flags]
Flags:
-h, --help help for set
Global Flags:
-s, --set string Set exampleCmd parameters. (default "default_param")
my init() function contains these two lines:
func init() {
...
exampleCmd.PersistentFlags().StringP("set", "s", defaultArgument, "Set parameters.")
exampleCmd.AddCommand(setCmd)
...
}
var exampleCmd = &cobra.Command{
Use: "set",
Short: "set parameter",
Long: `set parameter`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 && len(args) != 0 {
color.Red("Wrong usage, insert just a parameter")
} else if len(args) == 0 {
color.Yellow("Setting default parameter: " + defaultArgument)
internal.SetParams(defaultArgument)
} else {
internal.SetParams(args[0])
}
return nil
},
}
How can I accept parameters with dashes at beginning with cobra, if exists any solution?
As with virtual all Unix-style command line utilities and flag parsing libraries, Cobra separates flags from arguments with a --
, after which no more arguments will be parsed as flags, even if they start with a -
.
go run myapp exampleCmd set -- "-Dexample"
This is no different than how you interact with other CLI utilities. For example, rm -i
sets the interactive
flag, while rm -- -i
removes a file named -i
.
You definitely do not want to arbitrarily disable flags for certain commands or subcommands which is inconsistent (both within your own app and across all other apps), unnecessary, and breaks basic user expectations: Sometimes, -h
will do what the user expects, but for some commands, for reasons the user cannot predict, -h
will be treated as an argument and produce unexpected behavior.
Unix has solved this problem for more than 50 years. Let the user decide whether a argument is a flag via --
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With