How to pass flags as arguments in cobra (golang)?

3.4k views Asked by At

I am using cobra to create a CLI application (app). I need to implement a behavior in which I can pass flags as arguments. These flags will be passed|used further to another application via exec.Command(). All flag arguments passed to app must be ignored by the app itself, i.e. not recognized as flags.

I do not rule out that this is strange behavior. But if there is an opportunity to implement I will be grateful.

Examples of interaction with the application:

> app --help
or
> app --first --second

I want the arguments (--help --first --second, and all others) to not be taken as flags for app.

1

There are 1 answers

3
The Fool On BEST ANSWER

You can pass them after a double dash -- which by convention indicates that following flags and args are not meant to be interpreted as args and flags for the main program. They are ignored unless you explicitly use them in some way. i.e.:

if len(pflag.Args()) != 0 {
    afterDash := pflag.Args()[pflag.CommandLine.ArgsLenAtDash():]
    fmt.Printf("args after dash: %v\n", afterDash)
}
$ go run ./cmd/tpl/ -d yaml -- --foo --bar
args after dash: [--foo --bar]

cobra is using the pflag package https://pkg.go.dev/github.com/spf13/pflag