Search code examples
bashcompletion

Is it possible to have separate bash completion functions for separate commands which happen to share the same name?


I have two separate scripts with the same filename, in different paths, for different projects: /home/me/projects/alpha/bin/hithere and /home/me/projects/beta/bin/hithere.

Correspondingly, I have two separate bash completion scripts, because the proper completions differ for each of the scripts. In the completion scripts, the "complete" command is run for each completion specifying the full name of the script in question, i.e.

complete -F _alpha_hithere_completion /home/me/projects/alpha/bin/hithere

However, only the most-recently-run script seems to have an effect, regardless of which actual version of hithere is invoked: it seems that bash completion only cares about the filename of the command and disregards path information.

Is there any way to change this behavior so that I can have these two independent scripts with the same name, each with different completion functions?

Please note that I'm not interested in a solution which requires alpha to know about beta, or which would require a third component to know about either of them--that would defeat the purpose in my case.


Solution

  • The Bash manual describes the lookup process for completions:

    If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. If those searches do not result in a compspec, any compspec defined with the -D option to complete is used as the default.

    So the full path is used by complete, but only if you invoke the command via its full path. As for getting completions to work using just the short name, I think your only option (judging from the spec) is going to be some sort of dynamic hook that determines which completion function to invoke based on the $PWD - I don't see any evidence that Bash supports overloading a completion name like you're envisioning.