Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use bash completion-functions that are defined on-the-fly?

I try to add a completion for the alias: alias m='man'.
So, I added complete -F _man m to my .bashrc.

The problem is that the function _man used for completing, isn't defined at the start of the bash session but is defined when performing the first tab-competition on the $ man command.
So: $ complete -p | grep _man can either return nothing, or return:

complete -F _man man
complete -F _man apropos
complete -F _man whatis

Therefore, when I try to tab-complete on $ m command, I can get:

$ m -bash: completing : function « _man » not found
$ m

And I have the same problem with the functions _aptitude and _apt-get


What I would like, is to use my .bashrc to force the creation of the functions _man, _aptitude, _apt-get as soon as bash starts.
Maybe it is possible using compgen builtin.

My bash version is:
GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)

Thanks for reading.


Edit: In fact, a similar question already exists and has been answered:
- bash-completion - completion function defined the first time a command is invoked -

like image 517
loxaxs Avatar asked Oct 02 '22 10:10

loxaxs


1 Answers

You have in your .bashrc:

alias m='man'
complete -F _man m

Just add :

_completion_loader man

Then your completions on $ m will work fine, even without performing tab-completion on $ man before.

_completion_loader may not be defined in your distribution. Here's a copy of the code found in a .bashrc of Ubuntu 14.04:

_completion_loader () 
{ 
    local compfile=./completions;
    [[ $BASH_SOURCE == */* ]] && compfile="${BASH_SOURCE%/*}/completions";
    compfile+="/${1##*/}";
    [[ -f "$compfile" ]] && . "$compfile" &> /dev/null && return 124;
    complete -F _minimal "$1" && return 124
}

Actually, to avoid generating the _man function twice, you should also change the line
complete -F _man m to
complete -F _man man m.

like image 119
loxaxs Avatar answered Oct 17 '22 00:10

loxaxs