Install
# compgen is a Bash builtin. It is available whenever you are using bash.
What it does
compgen prints possible completions for a given prefix or category. It is the workhorse behind many programmable completion functions, and it is also useful on its own for listing things Bash “knows about” (commands, aliases, variables, users, etc.).
How it works (mechanical)
- Runs inside Bash and queries built-in tables for commands, variables, functions, aliases, etc.
- Can generate filesystem matches (files/directories) using Bash’s glob logic.
- Can generate matches from a word list (
-W) or from a function used bycomplete. - Most often used inside completion functions to populate
COMPREPLY. - Output is plain text — you can pipe it into tools like
sort,grep,fzf, etc.
Quick Start
# List all available commands in PATH + shell builtins compgen -c | head
10 Practical Examples
# 1) List commands (PATH + builtins) matching a prefix compgen -c sys
# 2) List only builtins compgen -b
# 3) List only aliases compgen -a
# 4) List shell functions compgen -A function
# 5) List variables (environment + shell vars) compgen -v | head
# 6) List users from /etc/passwd (handy for admin scripting) compgen -u | head
# 7) List groups compgen -g | head
# 8) List files matching a prefix (filesystem completion) compgen -f /etc/ho
# 9) Generate completions from a custom word list compgen -W "start stop status restart reload" -- st
# 10) Use compgen inside a completion function (minimal example)
_mytool_complete() {
local cur="${COMP_WORDS[COMP_CWORD]}"
COMPREPLY=( $(compgen -W "start stop status restart" -- "$cur") )
}
complete -F _mytool_complete mytoolNotes & Gotchas
- Because it is a Bash builtin, it won’t work if you’re in
shor another shell. - Some categories use
-A(like-A function), others have short flags (-c,-u, etc.). - Output can be large; pipe to
head,less,sort -u, etc. - When used in completion scripts, always quote
$curand use--before it. - For real completions, pair it with
completeand optionalbash-completionpackage.
Historical Context
Bash introduced programmable completion to move beyond simple filename completion. compgen became the low-level generator that completion scripts use to list valid candidates efficiently.
Modern Equivalent
Bash’s completion ecosystem is still very active (especially on servers). Other shells like zsh
and fish provide different completion frameworks, but compgen remains central for Bash.
Related Commands
- complete — register completion rules for commands.
- compopt — adjust completion behavior from inside a completion function.
- bind — Readline key bindings (Tab invokes completion).
- type — identify how a command name is resolved (builtin/alias/file/function).
- declare — inspect variables/functions that compgen can list.