# How to generate shell completions for bash, zsh, and fish

> Ship a completion command that prints scripts for bash, zsh, fish, and PowerShell, and complete resource names from your API behind a cache and a short timeout.

Source: https://voxgig.com/howto/shell-completions-for-bash-zsh-and-fish

- Audience: api-producer
- Level: intermediate
- Languages: go, python, typescript, rust
- Verified: 2026-11-30
- Published: 2026-11-30

## 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](https://pkg.go.dev/github.com/spf13/cobra@v1.10.2#Command) 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`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-completion.html) | 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`](https://docs.rs/clap_complete/4.6.12/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](https://click.palletsprojects.com/en/stable/shell-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)](https://github.com/spf13/cobra/blob/v1.10.2/site/content/completions/_index.md) | 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](https://github.com/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](https://docs.stripe.com/cli/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.

```go title="main.go"
	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:

```bash
go run . completion --help
```

```text output
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](https://cli.github.com/manual/gh_completion) as
`gh completion -s <shell>`, and
[kubectl](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_completion/) 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.

```go title="complete.go"
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:

```bash
go run . __complete get --output ""
```

```text 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.

```bash
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](https://github.com/scop/bash-completion), 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](https://fishshell.com/docs/current/completions.html) 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:

```text title="records/click.txt"
_FLEET_COMPLETE=powershell_source, first line:
Register-ArgumentCompleter -Native -CommandName fleet -ScriptBlock {
Tab after 'fleet get w':
plain,web-1
plain,web-2
```

[typer](https://typer.tiangolo.com/features/) 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:

```text title="records/oclif.txt"
what the bash function knows about get:
get --output
```

clap's static script carries no server name at all. Its dynamic mode,
[`CompleteEnv`](https://docs.rs/clap_complete/4.6.12/clap_complete/env/index.html), answers from
the program:

```text title="records/clap.txt"
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`:

```bash
go test -v . | grep -E '^(=== RUN|PASS$|FAIL$)'
```

```text output
=== 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:

```bash
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
```

```text output
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:

```bash
FLEET_NO_SHIM=1 PATH="$PWD:$PATH" bash tab.sh 'fleet g'
```

```text output
/dev/fd/63: line 15: _get_comp_words_by_ref: command not found
```

Install the bash-completion package, which the
[kubectl page](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_completion/) 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

- [Add a --json flag and stable exit codes to a CLI](/howto/json-flag-and-stable-exit-codes)

- [Write CLI help that people and agents can both use](/howto/help-text-people-and-agents-can-use)

- [Map API parameters to CLI arguments and flags](/howto/map-api-parameters-to-cli-flags-and-arguments)

- [Build an oclif CLI with one topic per API resource](/howto/build-an-oclif-cli-with-topics-per-resource)

- [Sign and notarize a CLI binary for macOS](/howto/sign-and-notarize-a-cli-binary-for-macos)

## 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.

[^1]: cobra numbers its directives as powers of two, from `ShellCompDirectiveError` at 1 through
`ShellCompDirectiveKeepOrder` at 32, as the
[`ShellCompDirective`](https://pkg.go.dev/github.com/spf13/cobra@v1.10.2#ShellCompDirective)
constants show. The type is a bit map, so a function may combine them, and `:6` would mean no
space and no files. The sample only ever asks for the one bit.

[^2]: fish needs the least help of the three shells. Its
[documentation](https://fishshell.com/docs/current/completions.html) 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.

[^3]: The [reference page](https://docs.stripe.com/cli/completion) 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](https://github.com/stripe/stripe-cli/blob/v1.55.15/pkg/cmd/completion.go)
describes it as generating bash, zsh, and fish completion scripts, adds a `--write-to-stdout`
flag, and offers the three names to its own completion of `--shell`.