bashshellautocomplete

How to ensure that a lazily-loaded bash completion is loaded


I have my own script extending scp, with the same syntax. Naturally, I want to use the same autocomplete function. Following the suggestion in another question I added the following to .bash_aliases

complete -o nospace -F _scp my_scp

Unfortunately, if I type my_scp <tab> <tab> in the terminal, I get the error bash: completion: function `_scp' not found. If instead, I first type scp <tab> <tab> then the autocompletion function is loaded, and I can then use my_scp completion without a problem.

How do I ensure that the lazily-loaded function _scp is loaded when it is needed for my custom command?

ADDED IN RESPONSE TO A COMMENT: Output of complete -p my_scp scp before typing scp <tab> <tab> in the terminal:

complete -o nospace -F _scp my_scp
bash: complete: scp: no completion specification

Output of complete -p my_scp scp after typing scp <tab> <tab> in the terminal:

complete -o nospace -F _scp my_scp
complete -o nospace -F _scp scp

Similarly, type _scp gives bash: type: _scp: not found before, and a long source code after.


Solution

  • The function _scp is defined in /usr/share/bash-completion/completions/scp, to load it, put following in .bash_aliases :

    shopt -s extglob; source /usr/share/bash-completion/completions/scp