Bash – How do command-line tools have their own autocomplete list

autocompletebashUbuntu

How does Bash in Ubuntu know a tool's specific list of actions?

For example if I type apt-get and tab twice I only see remove, update, upgrade …etc, but not the actions for another command or the files in the current directory.

I'm developing a command-line tool in Go and would like to provide this feature for the distros that support it.

Best Answer

It does this using bash v4's completion features. The completion code for apt-get is provided by the bash-completion package and located at /usr/share/bash-completion/completions/apt-get. Applications that have completion and are not part of the base bash-completion package place their completion scripts in /etc/bash_completion.d.

The completions are loaded via sourcing /etc/bash_completion. Exactly where this is done will vary depending on Debian or Ubuntu versions. That in turn will source everything in /usr/share/bash-completion/completions and /etc/bash_completion.d.

Related Question