Skip to content

StringP flag parses next flag as value. #417

Open
@Hoodie-Huuuuu

Description

StringP flag doesn't check if next value -s another option.

package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
)

func main() {
	// Create the root command
	var rootCmd = &cobra.Command{
		Use:   "myapp",
		Short: "A sample application using Cobra",
		Long:  `This is a sample application demonstrating how to use the Cobra library for handling flags.`,
		Run: func(cmd *cobra.Command, args []string) {
			// Retrieve the flag value
			name, _ := cmd.Flags().GetString("name")
			if name != "" {
				fmt.Println("Hello, " + name + "!")
			} else {
				fmt.Println("Hello, stranger!")
			}
		},
	}

	// Add the stringP flag
	rootCmd.Flags().StringP("name", "n", "", "Name of the user")
	rootCmd.Flags().StringP("sname", "s", "", "Second name of the user")

	// Execute the command
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

when i run

go run ./main.go -n -s   

i get "Hello, -s!" instead error

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions