How to get [TAB] to work with arguments of aliases to autocomplete as can be done with the actual command

I have many aliases that I created in my .bash_aliases file, and they are very useful, so if I want all info on a package I do something like:

allinfo software-center

And that does the equivalent of:

apt-cache show software-center

As the alias is set as:

alias allinfo='apt-cache show'

But there is one disadvantage of this, I am currently unable to autocomplete with TAB when using allinfo instead of the actual command. So I was wondering if there was a way to overcome this disadvantage and make it so that doing allinfo software-ce[TAB] will work just the same as it does when you use it with the actual command, and not just make a large tab space?

I am using gnome-terminal.


OS Information:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 15.04
Release:    15.04
Codename:   vivid

Package Information:

gnome-terminal:
  Installed: 3.14.2-0ubuntu3
  Candidate: 3.14.2-0ubuntu3
  Version table:
 *** 3.14.2-0ubuntu3 0
        500 http://gb.archive.ubuntu.com/ubuntu/ vivid/main amd64 Packages
        100 /var/lib/dpkg/status

Solution 1:

Great question! If your allinfo command was the same as just apt-cache, (ie, without the show) then we could look at the completion for apt-cache, and apply that to your allinfo alias.

However, you want a subset of the apt-cache completion, so we have a little more work to do.

If we look in the completion definition for apt-cache - in /usr/share/bash-completion/completions/apt-cache, we see the following is used for the show subcommand:

        COMPREPLY=( $( apt-cache --no-generate pkgnames "$cur" 2> /dev/null ) )

- this is just setting the COMPREPLY variable to the list of matching packages.

So, we can borrow this and write our own function, and bind it to your allinfo alias:

# define a function to print the possible completions for
# an allinfo invocation
_allinfo()
{
    _init_completion || return
    COMPREPLY=($(apt-cache --no-generate pkgnames "$cur" 2>/dev/null))
    return 0
}

# bind the above completion function to the 'allinfo' alias
complete -F _allinfo allinfo

If you add that fragement to your .bashrc file, you should get the completions working as you expect.