Programmable completion
Programmable completion suggests candidate words before the user executes a command. complete registers a completion specification for a command name, compgen generates candidates, and compopt changes options for a specification or the current completion. A simple word list uses complete -W 'start stop status' bmtool. A completion function registered with complete -F receives completion context and fills the COMPREPLY array. COMP_WORDS and COMP_CWORD describe the tokenized command line and current word; COMP_LINE and COMP_POINT describe the full line and cursor position. Tokenization is influenced by COMP_WORDBREAKS. Completion is not input validation or authorization: users may type anything, so the command must still validate arguments. Completion functions run code in the interactive shell; prefer local finite computation and avoid untrusted commands, secrets, or unexpected side effects. These examples test candidate generation and registration, plus a direct function call with synthetic context; pressing Tab and actual cursor-context population are manual checks. A compgen invocation with no matches can return status 1. A successful sort at the end of a pipeline does not establish that candidate generation succeeded. For the fixed nonempty fixture, enable pipefail.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Generate prefix matches
set -o pipefailcompgen -W 'start stop status' -- st | LC_ALL=C sortExpected stdout:
startstatusstopThe fixed word list yields three matching candidates; sorting stabilizes display order.
Register and inspect a specification
complete -W 'start stop status' bmtool || exit 1complete -p bmtool >/dev/null || exit 1compopt -o nospace bmtool || exit 1complete -r bmtool || exit 1if complete -p bmtool >/dev/null 2>&1; then exit 1; fiprintf 'registered, updated, removed\n' Expected stdout:
registered, updated, removedRegistration and option changes are tested without invoking bmtool.
Test a completion function directly
_bm_complete() { local word candidate word=${COMP_WORDS[COMP_CWORD]} COMPREPLY=() for candidate in start stop status; do [[ $candidate == "$word"* ]] && COMPREPLY+=("$candidate") done return 0}complete -F _bm_complete bmtool || exit 1COMP_WORDS=(bmtool sta)COMP_CWORD=1_bm_completeprintf '%s\n' "${COMPREPLY[@]}"Expected stdout:
startstatusThe manually supplied context tests the function, not Readline itself.
Common mistakes
Do not execute the command being completed just to generate suggestions. Do not treat suggestions as an allowlist for actual invocation.
Practice
Create a completion function for show, list and reset-preview. Test prefixes directly with synthetic COMP_WORDS and COMP_CWORD, including a prefix with no matches; then register the function in a private interactive shell.
Next: Portability and standards