Bash – How does TAB auto-complete find options to complete
autocompletebash
And how does it also autocomplete aliases?
Best Answer
Depending on the command:
Someone may have written a function to generate possible completions of arguments, including options. You'll find functions for some commands in /etc/bash_completion.d/* (or a different location on some systems). These functions are registered with the completebuilt-in (e.g. complete -F _find find tells bash to call the _find function when you press Tab on a find command). They use the compgen built-in to tell bash “here are the possible completions”.
For some commands, bash will call the command with the argument --help and parse the output. Such commands can be registered with the complete built-in, e.g. complete -F _longopt ls. _longopt is in fact a completion generation function, that happens to parse a command's output rather than use a fixed list. (There are other more specialized completion functions that parse a command's output to generate possible completions; look in /etc/bash_completion.d/* for examples.)
For things like aliases, the completion function looks them up in bash's internal tables. The complete built-in has options for that, e.g. -A for aliases.
By issuing the command complete you'll get the list of all completion definitions. Then you can search the offending definition somewhere in /etc/bash_completion and /etc/bash_completion.d. There can be also some .bash_completion in your home directory. On my system the $HOME variable is completed properly, but then fails to complete anything.
Did you try to use ~ instead of $HOME? It's easier to type and it works as expected...
Best Answer
Depending on the command:
/etc/bash_completion.d/*
(or a different location on some systems). These functions are registered with thecomplete
built-in (e.g.complete -F _find find
tells bash to call the_find
function when you press Tab on afind
command). They use thecompgen
built-in to tell bash “here are the possible completions”.--help
and parse the output. Such commands can be registered with thecomplete
built-in, e.g.complete -F _longopt ls
._longopt
is in fact a completion generation function, that happens to parse a command's output rather than use a fixed list. (There are other more specialized completion functions that parse a command's output to generate possible completions; look in/etc/bash_completion.d/*
for examples.)complete
built-in has options for that, e.g.-A
for aliases.