Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-cobra

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.

like image 293
fabelx Avatar asked Oct 31 '25 03:10

fabelx


2 Answers

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

like image 109
The Fool Avatar answered Nov 01 '25 18:11

The Fool


it's an old question but maybe someone will benefit from it.

Cobras Command struct has a variable called DisableFlagParsing bool, by default it's false. When set to true, Cobra will stop parsing flags and pass them to args in the Run or any other Run-like command. -> Run func(cmd *Command, args []string)

Quote from documentation:

DisableFlagParsing disables the flag parsing. If this is true all flags will be passed to the command as arguments.

like image 39
zuzuske Avatar answered Nov 01 '25 18:11

zuzuske



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!