A user types fleet get and presses Tab, and the shell offers filenames from the working
directory, because nothing told it what get takes. The server names live in your API, so the
user opens a browser to copy one. Wire completion to the API carelessly and every Tab waits on a
slow authenticated call, and the prompt freezes.
What you get
You will end up with a completion command that prints a script for four shells, and server
names that complete from the API through a cache and a 300 ms timeout. This is for you if you
maintain a CLI over an API and its users type resource names by hand.
Short answer
In a cobra CLI, the completion command already prints a script for bash, zsh, fish, and
PowerShell. Set ValidArgsFunction on a command to complete resource names from your API, and
RegisterFlagCompletionFunc for flag values. Each Tab runs your binary through the hidden
__complete command, so cache the names per API and credential, time the request out after a
few hundred milliseconds, and test by calling __complete directly.
You will need
Go 1.24 or later and a CLI with at least one command below its root. Users of bash need the bash-completion
package, which cobra’s bash script calls into. The sample is fleet, a Go CLI on
cobra whose get command takes a
server name from GET /servers. The other rows were run once by record.sh, apart from the
Stripe CLI and the AWS CLI version 2.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
aws_completer | A helper program bash calls through complete -C, with no script to generate | Each user adds a complete line by hand, and version 1 offered no resource names | Your users run fish, which the AWS page sets up nothing for, or want a script per shell |
clap_complete | A Rust CLI on clap, with static scripts for five shells from generate | Dynamic names need the unstable-dynamic feature, whose shell interface may change between releases | Your CLI is not Rust, or dynamic values must rest on a stable interface |
| click and typer completion | A Python CLI, where one environment variable makes the program print its own script | Every Tab starts the interpreter and imports your CLI, so import time becomes completion delay | Users expect a completion command, or the CLI imports slowly |
| cobra completion (gh, kubectl) | A Go CLI, with four shells and a hidden __complete command from the library | Every Tab runs your binary and whatever it calls, and bash needs bash-completion installed | Completion must work with no program call, from a script alone |
| oclif plugin-autocomplete | A TypeScript CLI on oclif, with commands and flags completed from a cache file | No fish script, and the cache holds no argument values, so names never complete | You need fish, or values fetched from the API |
| stripe completion | You use the Stripe CLI and want its commands on Tab | It writes a file you move by hand, from a cobra bash script of the legacy kind | You are building your own CLI, where the library rows apply |
cobra and click answer Tab by running the program, which is what makes dynamic names possible
and what makes a slow API a slow prompt. oclif’s plugin writes everything into cache files when
fleet autocomplete runs, so a Tab never runs the CLI, at the price of no argument values. clap offers
both: static generate scripts, and a dynamic mode behind a feature its documentation marks
unstable.
Add the completion command and a dynamic argument
cobra adds completion to a root command that has commands below it, unless
CompletionOptions.DisableDefaultCmd is set. The work is on the command
whose argument comes from the API: a ValidArgsFunction for the server name, and a fixed list
for the --output flag.
get := &cobra.Command{
Use: "get SERVER",
Short: "Show one server",
Args: cobra.ExactArgs(1),
ValidArgsFunction: completeServerNames,
RunE: func(cmd *cobra.Command, args []string) error {
output, _ := cmd.Flags().GetString("output")
return getServer(cmd.OutOrStdout(), apiBase(cmd), args[0], output)
},
}
get.Flags().StringP("output", "o", "table", "output format: table, json or yaml")
_ = get.RegisterFlagCompletionFunc("output", cobra.FixedCompletions(
[]cobra.Completion{"table", "json", "yaml"}, cobra.ShellCompDirectiveNoFileComp))
The generated command lists one script per shell:
go run . completion --help
Generate the autocompletion script for fleet for the specified shell.
See each sub-command's help for details on how to use the generated script.
Usage:
fleet completion [command]
Available Commands:
bash Generate the autocompletion script for bash
fish Generate the autocompletion script for fish
powershell Generate the autocompletion script for powershell
zsh Generate the autocompletion script for zsh
Flags:
-h, --help help for completion
Global Flags:
--api string base URL of the fleet API (default $FLEET_API, then http://127.0.0.1:8080)
Use "fleet completion [command] --help" for more information about a command.
Both large cobra CLIs expose it: gh as
gh completion -s <shell>, and
kubectl as
kubectl completion <shell>, each for bash, zsh, fish, and PowerShell.
Cache the names and give up fast
Every script cobra generates sends the line to fleet __complete and reads candidates back, so
the completion function runs once per Tab. It answers from a cache file younger than 60
seconds. Otherwise it asks the API with a 300 ms deadline, and keeps a stale list when the API
does not answer.
func cachedServerNames(ctx context.Context, api, token, dir string, now time.Time) ([]string, error) {
var file string
var stale []string
if dir != "" {
file = cacheFile(dir, api, token)
if info, err := os.Stat(file); err == nil {
if names, err := readCache(file); err == nil {
if now.Sub(info.ModTime()) < cacheTTL {
return names, nil
}
stale = names
}
}
}
names, err := fetchServerNames(ctx, api, token, completionTimeout)
if err != nil {
return stale, err
}
cacheFile hashes the API address and the token into the filename, so two accounts on one
machine never share a list. Names outside [A-Za-z0-9._-] are dropped, because a newline inside
one would split it into two candidates.
Ask the program directly, as the shell would:
go run . __complete get --output ""
table
json
yaml
:4
The last line is the directive.1 4 tells the shell to offer no filenames when the list is
empty.
Install the script for each shell
A script can be sourced from ~/.bashrc on every start, source <(fleet completion bash), which
always matches the installed binary and costs one process per shell start. Written once into a
completion directory, it loads only when the user first completes fleet, and it goes stale on
upgrade unless the package manager rewrites it.
fleet completion bash > ~/.local/share/bash-completion/completions/fleet
fleet completion zsh > "${fpath[1]}/_fleet"
fleet completion fish > ~/.config/fish/completions/fleet.fish
The bash directory is the per-user one in the
bash-completion README, loaded on demand. zsh finds
_fleet on fpath once compinit runs, which cobra’s completion zsh --help reminds the user
to enable. fish loads automatically any file
named after the command in its completions directory.2
Compare what the other tools offer on the same Tab
record.sh built the same get command in each library and pressed Tab through its protocol.
click prints its script when _FLEET_COMPLETE is set, and a shell_complete callback supplies
the names:
_FLEET_COMPLETE=powershell_source, first line:
Register-ArgumentCompleter -Native -CommandName fleet -ScriptBlock {
Tab after 'fleet get w':
plain,web-1
plain,web-2
typer builds on click and adds
--install-completion and --show-completion to the program itself, for five shell names:
bash zsh fish powershell pwsh. oclif’s plugin wrote bash, zsh, and PowerShell files, and its
bash function knows the command and its flag, nothing more:
what the bash function knows about get:
get --output
clap’s static script carries no server name at all. Its dynamic mode,
CompleteEnv, answers from
the program:
static bash script, lines naming a server:
0
static bash script, the --output values:
table json yaml
COMPLETE=bash, Tab after 'fleet get w':
web-1
web-2
The AWS CLI version 1 completed aws s3 l to ls and returned nothing after aws s3 ls . Its
documentation says resource values complete in version 2 only. The Stripe CLI’s source
generates its bash script with cobra’s legacy GenBashCompletion.3
Check it worked
The tests drive __complete in process against a stand-in API on 127.0.0.1, and TestBashTab
sources the real bash script and presses Tab through tab.sh:
go test -v . | grep -E '^(=== RUN|PASS$|FAIL$)'
=== RUN TestSubcommandCompletes
=== RUN TestFlagNameCompletes
=== RUN TestFlagValueCompletes
=== RUN TestServerNamesComeFromTheAPI
=== RUN TestUnsafeNamesAreNotOffered
=== RUN TestSecondTabIsServedFromTheCache
=== RUN TestCacheIsKeptPerCredential
=== RUN TestSlowAPIGivesUpFast
=== RUN TestStaleCacheIsUsedWhenTheAPIIsDown
=== RUN TestCacheLifetimeOnAControlledClock
=== RUN TestHungAPIDoesNotHangBashTab
=== RUN TestServerNameIsOneEscapedPathSegment
=== RUN TestEveryShellGetsAScript
=== RUN TestBashTab
PASS
Press Tab yourself after a known command prefix, a known flag prefix, and a flag value:
go build -o fleet . && for line in 'fleet g' 'fleet get --o' 'fleet get --output j'; do PATH="$PWD:$PATH" bash tab.sh "$line"; done
get
--output
json
The zsh, fish, and PowerShell scripts are checked for their registration lines only.
When it goes wrong
Tab prints an error in bash. cobra’s script calls _get_comp_words_by_ref, a function from
bash-completion, and a shell without that package has none:
FLEET_NO_SHIM=1 PATH="$PWD:$PATH" bash tab.sh 'fleet g'
/dev/fd/63: line 15: _get_comp_words_by_ref: command not found
Install the bash-completion package, which the
kubectl page also
tells its users to do. tab.sh carries a small stand-in for that function so the test runs anywhere.
The prompt hangs for seconds. The completion function made an authenticated call with no
deadline. TestSlowAPIGivesUpFast points fleet at a stand-in that takes five seconds and fails
if Tab waits longer than two. TestHungAPIDoesNotHangBashTab presses Tab in bash against one that
never answers.
Completions stop matching the commands after an upgrade. A script written to a file describes the binary that wrote it. clap’s documentation warns about this for its dynamic mode, and advises generating the script at each shell start.
When not to do this
Do not fetch from the API on Tab for a list that changes once a release, such as regions or output formats. A fixed list costs nothing per key press and works offline.
Do not complete names that need a login the user may not have. A completion function cannot prompt, so an expired token turns every Tab into a silent timeout. Read the token you already stored, and offer nothing when it is missing.
Do not ship the dynamic mode of clap_complete to users who pin versions of your CLI for
years. Its own documentation calls the interface unstable. The static scripts from generate
carry no such warning.
Skip cobra’s bash script if most of your users run bash without bash-completion, such as the
Bash 3.2 that macOS includes before Homebrew adds the package. click’s bash script calls no bash-completion function, and complete -C with
a helper program needs none either.
Related how-tos
Last verified
Verified 2026-11-30 against Go 1.24.7 and 1.25.14, cobra 1.10.2, GNU bash 5.2.21, Python 3.12.3, click 8.5.1,
typer 0.29.3, awscli 1.46.3, Node 22.23.5, @oclif/plugin-autocomplete 4.0.6, Rust 1.97.0, and
clap_complete 4.6.12. Every output block is what the command preceding it printed, and the
records/ files are what record.sh wrote. zsh, fish, and PowerShell were not installed, so
their scripts were generated and checked but never sourced. The Stripe CLI was not run, because
its module declares a replace directive and go install refuses it; its row comes from its
reference page and its source at v1.55.15. gh, kubectl, and the AWS CLI version 2 were not run,
and what the page says of them comes from their documentation.
Footnotes
-
cobra numbers its directives as powers of two, from
ShellCompDirectiveErrorat 1 throughShellCompDirectiveKeepOrderat 32, as theShellCompDirectiveconstants show. The type is a bit map, so a function may combine them, and:6would mean no space and no files. The sample only ever asks for the one bit. ↩︎ Back to text -
fish needs the least help of the three shells. Its documentation lists six places it looks for completions, and the last is a directory of completions it generates by itself from the system’s manual pages. A command with a man page can arrive with completions its author never wrote. ↩︎ Back to text
-
The reference page says the Stripe CLI supports autocompletion with the bash and zsh shells, and lists those two values for
--shell. The command’s own source at v1.55.15 describes it as generating bash, zsh, and fish completion scripts, adds a--write-to-stdoutflag, and offers the three names to its own completion of--shell. ↩︎ Back to text