如何让 [TAB] 使用别名的参数来自动完成,就像使用实际命令一样

9 command-line bash alias

我在我的.bash_aliases文件中创建了许多别名,它们非常有用,所以如果我想要一个包的所有信息,我会执行以下操作:

allinfo software-center
Run Code Online (Sandbox Code Playgroud)

这相当于:

apt-cache show software-center
Run Code Online (Sandbox Code Playgroud)

由于别名设置为:

alias allinfo='apt-cache show'
Run Code Online (Sandbox Code Playgroud)

但这有一个缺点,我目前无法TAB在使用allinfo而不是实际命令时自动完成。所以我想知道是否有办法克服这个缺点并使它的allinfo software-ce[TAB]工作与实际命令一起使用时的效果相同,而不仅仅是制作一个大的制表符空间?

我正在使用gnome-terminal.


操作系统信息:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 15.04
Release:    15.04
Codename:   vivid
Run Code Online (Sandbox Code Playgroud)

包装信息:

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
Run Code Online (Sandbox Code Playgroud)

Jer*_*err 6

好问题!如果您的allinfo命令与 , 相同apt-cache(即,没有show),那么我们可以查看 的完成情况apt-cache,并将其应用于您的allinfo别名。

但是,您需要apt-cache完成的子集,因此我们还有一些工作要做。

如果我们看一下在完成定义apt-cache-中/usr/share/bash-completion/completions/apt-cache,我们看到了以下用于show子命令:

        COMPREPLY=( $( apt-cache --no-generate pkgnames "$cur" 2> /dev/null ) )
Run Code Online (Sandbox Code Playgroud)

- 这只是将COMPREPLY变量设置为匹配包的列表。

因此,我们可以借用它并编写我们自己的函数,并将其绑定到您的 allinfo 别名:

# 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
Run Code Online (Sandbox Code Playgroud)

如果您将该片段添加到您的.bashrc文件中,您应该使完成工作按您的预期工作。