4

I'm looking for an easy way to "inherit" Bash completion functions from a program into a script.

Say there's a program foo that provides its own Bash completion, such that $ foo sub<TAB> completes to $ foo subcommand. Now I want to write a script foo-extra that takes the same arguments as foo, doing some extra stuff before calling foo <arguments>. What's the easiest way to make the foo-extra script piggy-back on foo's completion function?

darkfeline
  • 9,404
  • 5
  • 31
  • 32

1 Answers1

6

Your foo completes using a certain function (if standard, it would be usually defined in /usr/share/bash-completion/completions/foo, and possibly called something like _foo). The command that makes a function a completion function is:

complete -F _foo foo

You can co-opt the same function to an arbitrary command:

source /usr/share/bash-completion/completions/foo
complete -F _foo foo-extra
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    I actually needed a solution for ZSH, but I asked for Bash because it is a more common shell. For reference, I got this to work using ZSH's version of the `complete` command called `compdef`: `compdef _foo foo-extra` Thanks for your helpful answer though, it answered my question perfectly. – darkfeline Jul 08 '15 at 03:02
  • Sadly, I don't see a way to say "complete foo-extra as foo" without knowing what foo's completion function is. `complete -p foo` tells me, but only after it has been loaded, therefore it's unsafe to run `$(complete -p foo |awk '{$NF="foo-extra";print}')` (which will give you `bash: complete: foo: no completion specification`) – Adam Katz Oct 09 '22 at 03:27