为什么这个自动完成功能不能在Linux中自动完成?

时间:2013-02-06 07:15:21

标签: bash ubuntu autocomplete

在我的bashrc中。我正在尝试按以下方式完成命令scp

function _scp_complete
{
  COMPREPLY=""
  COMPREPLY+=( $(cat ~/.ssh_complete ) )
  COMPREPLY+=( $( find . ! -name . -prune -type f ) )
}
complete -F _scp_complete scp

我的想法是,当按scp [tab]时,我会看到当前目录中的所有文件以及文本文件~/.ssh_complete中列出的单词。我们假设此文件包含以下条目:

alex@192.0.0.1 alex@192.0.0.2

所需的行为如下:我输入scp alex@[TAB]并选项卡'完成'命令到scp alex@192.0.0。自动,因为只有两个可能的参数以alex @开头(假设当前工作目录中没有类似的命名文件。):

>scp alex@[TAB]
  alex@192.0.0.1 alex@192.0.0.1 
>scp alex@192.0.0.

我使用所描述的实现获得的行为如下:我键入scp alex@[TAB]并且标签完成完成任何操作,但列出命令下面的所有可能参数:

>scp alex@[TAB]
  alex@192.0.0.1 alex@192.0.0.1 file1 Music Pictures ./.emacs <ALL files in the current directory>
>scp alex@

如何修复该功能以获得所需的行为?

1 个答案:

答案 0 :(得分:1)

您需要使用COMP_WORDS数组来获取已键入的当前单词。然后使用compgen命令根据原始单词列表生成可能的完成。

尝试以下方法:

_scp_complete()
{
  local cur=${COMP_WORDS[COMP_CWORD]}
  COMPREPLY=( $(compgen -W "$(< ~/.ssh_complete) $( find . ! -name . -prune -type f )" -- $cur) )
}
complete -F _scp_complete scp

请查看此博客文章了解更多详情:Writing your own Bash Completion Function

请注意,我认为此完成不适用于名称中包含空格的文件。

另请注意,使用$(cat file)从文件中提取文本效率更高,而不是$(< file)