Skip to content

Issue passing local flag to subcommand #1825

@IvanRibakov

Description

@IvanRibakov

I have a root command with persistent flag and a subcommand with a local flag. When executing subcommand, I seem to be unable to pass the local flag. No matter how I do it, I get Error: unknown flag:.

Here's the minimal example that reproduces my situation:

package main

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

var (
	testFlag string
	subFlag bool
	rootCmd = &cobra.Command{
		Use:   "root",
	}
)

func init() {
	rootCmd.PersistentFlags().StringVar(&testFlag, "rootFlag", "", "")

	subCmd := &cobra.Command{
		Use:   "subcommand",
	}
	subCmd.LocalFlags().BoolVar(&subFlag, "subFlag", false, "")
	subCmd.RunE = func(cmd *cobra.Command, args []string) error {
		fmt.Println(testFlag)
		fmt.Println(subFlag)
		return nil
	}

	rootCmd.AddCommand(subCmd)
}

func main() {
	rootCmd.Execute()
}

All of the above invocations produce an error Error: unknown flag: --subFlag:

$ go run . subcommand --rootFlag blah --subFlag
$ go run . subcommand --subFlag --rootFlag blah
$ go run . --rootFlag blah subcommand --subFlag

Can someone please explain me what am I missing here?

Metadata

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