The compgen command in Linux is a powerful but lesser-known tool used to generate lists of possible command completions. It’s mainly used behind the scenes for tab completion in Bash, but you can also use it directly for scripting and exploration.
🔎 What is compgen?
compgen stands for completion generator.
👉 It outputs lists of:
- Commands
- Aliases
- Built-ins
- Filenames
- Variables
✅ Basic Syntax
compgen [option]
📜 List Available Commands
compgen -c
👉 Shows all executable commands in your $PATH
📁 List Files in Current Directory
compgen -f
📂 List Directories Only
compgen -d
🧠 List Shell Built-ins
compgen -b
🔗 List Aliases
compgen -a
🔣 List Environment Variables
compgen -v
🔍 Filter Results (Search)
compgen -c | grep ssh
👉 Shows commands related to ssh
🎯 Match Specific Prefix
compgen -c ls
👉 Lists commands starting with ls
🚀 Real-World Uses
- Explore available commands quickly
- Build auto-completion scripts
- Debug Bash completion issues
- Generate dynamic lists in scripts
⚠️ Common Notes
- Output can be very large (especially
-c) - Best used with filters like
grep - Primarily useful in Bash scripting
🧠 Pro Tips
Combine with
sort:compgen -c | sortCount commands:
compgen -c | wc -l- Use in scripts for dynamic input suggestions
👍 Quick Summary
compgengenerates completion lists- Works with commands, files, variables, and more
- Useful for scripting and discovery
- Often used with pipes (
|) for filtering
🎯 Final Thoughts
While most users rely on tab completion without thinking about it, compgen gives you direct control over how those completions work. It’s especially useful for advanced users, shell customization, and scripting.