【问题标题】:Why is this auto complete function not auto-completing in Linux?为什么这个自动完成功能在 Linux 中不能自动完成?
【发布时间】:2013-02-06 07:15:20
【问题描述】:

在我的 bashrc 中。我正在尝试 bash 完成命令 scp 如下

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

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

亚历克斯@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@

如何修复函数以获得所需的行为?

【问题讨论】:

    标签: bash ubuntu autocomplete


    【解决方案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

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

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

    【讨论】:

    • 感谢您的帮助和解释!
    猜你喜欢
    • 2017-05-04
    • 2011-07-07
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多