I hope to get the false value, but always get true from toggle and tog boolean varaibles.
$ ./demo --toggle false --tog false
I hope get the following answer:
tog= false err=
toggle= false
But I got the following one:
tog= true err=
toggle= true
here is the demo code:
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var (
toggle bool
)
var RootCmd = &cobra.Command{
Use: "demo",
Run: func(cmd *cobra.Command, args []string) {
tog, err := cmd.Flags().GetBool("tog")
fmt.Println("tog=", tog, " err=", err)
fmt.Println("toggle=", toggle)
},
}
func init() {
RootCmd.PersistentFlags().BoolVarP(&toggle, "toggle", "t", false, "toggle bool")
RootCmd.Flags().BoolP("tog", "o", false, "tog bool")
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
is there any error in above codes ?
I made some minor changes to your program and hopefully this explains things. Basically, booleans can only take arguments via --bool=[true|false] or for short names -b=[true|false]. You cannot use --bool [true|false] nor can you use the shorthand -b[true|false]. For flags with NoOptDefVal pflag is unable to tell if the argument was meant for the flag or if it was meant for the generic args []string
$ ./test
args: []string{}
tog: false
toggle: false
$ ./test --tog
args: []string{}
tog: true
toggle: false
$ ./test --tog --toggle
args: []string{}
tog: true
toggle: true
$ ./test --tog false --toggle
args: []string{"false"}
tog: true
toggle: true
$ ./test --tog false --toggle false
args: []string{"false", "false"}
tog: true
toggle: true
$ ./test --tog=false --toggle=false
args: []string{}
tog: false
toggle: false
I got it, Thank you very much. @eparis
Most helpful comment
I made some minor changes to your program and hopefully this explains things. Basically, booleans can only take arguments via
--bool=[true|false]or for short names-b=[true|false]. You cannot use--bool [true|false]nor can you use the shorthand-b[true|false]. For flags withNoOptDefValpflag is unable to tell if the argument was meant for the flag or if it was meant for the genericargs []string