← Recipes

阅读中文版本

Add Bash Shell Completion

Ship a completion script that suggests subcommands and flags so users discover options without reading docs.

~25 minclibashux

Task

Write and install a bash completion script for the CLI.

When to use this

Users mistype subcommand names because there is no tab completion, slowing everyday use.

Prerequisites

  • A bash shell
  • A CLI with subcommands
  • A place to install the script

Steps

1. Define completions for commands and flags.

_tool_completions() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  if [ "$COMP_CWORD" -eq 1 ]; then
    COMPREPLY=( $(compgen -W "sync list config" -- "$cur") )
    return
  fi
  COMPREPLY=( $(compgen -f -- "$cur") )
}
complete -F _tool_completions tool

Expected output: Tab after the command name suggests sync, list, and config.

2. Source it and verify completion.

source completion.bash
tool sy<Tab>  # completes to sync

Expected output: Partial commands complete to valid subcommands.

Troubleshooting

Problem

Completion not loading

Solution

Ensure the script is sourced from the shell rc file for interactive shells.

Problem

Options behave oddly with paths

Solution

Branch completion by position and fall back to file completion carefully.

Limitations

  • Bash completion differs from zsh and fish.
  • Maintaining completions by hand is error-prone.
  • Does not validate argument values.

What this recipe does

Write and install a bash completion script for the CLI.

Users mistype subcommand names because there is no tab completion, slowing everyday use.

Prerequisites

  • A bash shell
  • A CLI with subcommands
  • A place to install the script

Procedure

  1. Define completions for commands and flags.
_tool_completions() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  if [ "$COMP_CWORD" -eq 1 ]; then
    COMPREPLY=( $(compgen -W "sync list config" -- "$cur") )
    return
  fi
  COMPREPLY=( $(compgen -f -- "$cur") )
}
complete -F _tool_completions tool

Expected result: Tab after the command name suggests sync, list, and config.

  1. Source it and verify completion.
source completion.bash
tool sy<Tab>  # completes to sync

Expected result: Partial commands complete to valid subcommands.

How to confirm it worked

Run the commands above and confirm every expected result in order. If a step does not produce the stated output, use the troubleshooting notes before continuing. A passing run shows tab completion suggests valid subcommands and adding a new subcommand updates the completion list.

Troubleshooting

Completion not loading — Ensure the script is sourced from the shell rc file for interactive shells.

Options behave oddly with paths — Branch completion by position and fall back to file completion carefully.

Limitations

  • Bash completion differs from zsh and fish.
  • Maintaining completions by hand is error-prone.
  • Does not validate argument values.