If one sets for a command
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"foo", "bar", "baz"}, cobra.ShellCompDirectiveFilterFileExt
},
...and
var foo string
serveCmd.Flags().StringVarP(&foo, "hello", "H", "", "Hello the world")
_ = serveCmd.MarkFlagRequired("hello")
...the resulting completion does not work properly. The required flag(s) get passed "eagerly" to the bash completion filedir function which does not understand the flag, and fails.
With current bash-completion main branch
$ ./my-cli serve <TAB>
[...]
+ __my-cli_debug $'The completions are: --hello\tHello the world\n-H\tHello the world\nfoo\nbar\nbaz\n'
[...]
+ _filedir '--hello|Hello|the|world|-H|Hello|the|world|foo|bar|baz|'
[...]
bash_completion: _comp_compgen_filedir: usage error
A complete example file in a cobra-cli generated project
Details
/*
Copyright © 2026 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("serve called")
},
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"foo", "bar", "baz"}, cobra.ShellCompDirectiveFilterFileExt
},
}
func init() {
var foo string
serveCmd.Flags().StringVarP(&foo, "hello", "H", "", "Hello the world")
_ = serveCmd.MarkFlagRequired("hello")
rootCmd.AddCommand(serveCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// serveCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
The description here is a specific one, I have not tried out or thought if this might happen with some other configuration combinations. This is with cobra v1.10.2.
If one sets for a command
...and
...the resulting completion does not work properly. The required flag(s) get passed "eagerly" to the bash completion filedir function which does not understand the flag, and fails.
With current bash-completion main branch
A complete example file in a cobra-cli generated project
Details
The description here is a specific one, I have not tried out or thought if this might happen with some other configuration combinations. This is with cobra v1.10.2.