Summary
compgen generates possible completions for a word. While primarily known for interactive tab-completion, it's actually useful in scripts for word matching, filtering, and variable/function introspection.
Requested Flags
| Flag |
Description |
-W wordlist |
Match against the given word list |
-v |
Match variable names |
-A function |
Match function names |
-A builtin |
Match builtin command names |
-A command |
Match all command names (builtins + functions) |
-A variable |
Match variable names (same as -v) |
-A file |
Match filenames in current directory |
-A directory |
Match directory names |
-P prefix |
Add prefix to each match |
-S suffix |
Add suffix to each match |
Use Cases
# Filter words by prefix
compgen -W "start stop restart reload" -- "re"
# Output: restart, reload
# List all variables starting with "BASH"
compgen -v BASH
# Output: BASH_VERSION, BASHPID, BASH_REMATCH, ...
# List all defined functions
compgen -A function
# List all builtins
compgen -A builtin
# Check if a command exists
if compgen -A command -- "git" > /dev/null; then
echo "git is available"
fi
# Build dynamic menus
options=$(compgen -W "$available_commands" -- "$user_input")
Implementation Notes
- Does NOT require interactive shell or readline
- Should query interpreter's variable store, function table, and builtin registry
-A file and -A directory should query VFS
- Each match printed on separate line to stdout
- Exit 0 if matches found, 1 if no matches
complete builtin (companion) is lower priority — compgen is the scriptable one
Summary
compgengenerates possible completions for a word. While primarily known for interactive tab-completion, it's actually useful in scripts for word matching, filtering, and variable/function introspection.Requested Flags
-W wordlist-v-A function-A builtin-A command-A variable-A file-A directory-P prefix-S suffixUse Cases
Implementation Notes
-A fileand-A directoryshould query VFScompletebuiltin (companion) is lower priority —compgenis the scriptable one