Many features that come with Linux and other Unix-type systems are non-obvious and almost indiscoverable. To put it another way, unless someone points out a feature or you RTFM a lot, you’ll miss a wealth of features under the surface. One feature I’d been missing for years is
compgen, a GNU Bash builtin that shows all possible completions.
To get everybody up to speed–when I say completions, what I mean is command names, paths, and so on, that might be completed when given a part of a string. For example when you’re typing a command and start with “apr”, you could get
apropos on an Ubuntu system. To figure this out using
compgen you could use
compgen -c | grep apr. To quickly figure out all directories, you could
cd to in a directory, just use
compgen -d. (Or
compgen -d | sort if you want a neat list…)
compgen -d is not limited to the present working directory. Run
compgen -d /etc/ for example, (or use in a script), and you get a full list of directories under
/etc. The closing
/ is necessary, by the way.
compgen utility is often used in scripts, but it can also be handy just to figure out what commands are installed on a system. Run
compgen -c, and you’ll get a full list of all commands. Run
compgen -a, and you should see any system-wide aliases.
You can also get all variable names using
compgen like so:
Curious how you’d use this in a script? There’s a good post by Adam Backstrom about using Bash’s programmable completion in a script.
Wondering what commands have keybindings? Use
compgen -A binding.
compgen works hand in hand with the
complete builtin. Both
compgen could do with much better documentation.
But if you’ve been working with Bash and never used
compgen, now’s a good time to take a look. It’s a really useful little utility/builtin to have at your fingertips.
Joe ‘Zonker’ Brockmeier is a freelance writer and editor with more than 10 years covering IT. Formerly the openSUSE Community Manager for Novell, Brockmeier has written for Linux Magazine, Sys Admin, Linux Pro Magazine, IBM developerWorks, Linux.com, CIO.com, Linux Weekly News, ZDNet, and many other publications. You can reach Zonker at firstname.lastname@example.org and follow him on Twitter.