【问题标题】:Customize tab completion in shell在 shell 中自定义选项卡完成
【发布时间】:2012-06-12 03:54:55
【问题描述】:

这可能比“自定义选项卡完成”有更好的名称,但情况如下:

通常,当我在命令行输入命令,然后输入两次 {TAB} 时,我会得到当前目录中所有文件和子目录的列表。例如:

[user@host tmp]$ cat <TAB><TAB>
chromatron2.exe                  Fedora-16-i686-Live-Desktop.iso  isolate.py
favicon.ico                      foo.exe                          James_Gosling_Interview.mp3

但是,我注意到至少有一个程序以某种方式过滤了此列表:wine。考虑:

[user@host tmp]$ wine <TAB><TAB>
chromatron2.exe  foo.exe

它有效地将结果过滤到*.exe。

认为它可能是某种负责过滤的包装脚本,做了一个which 和file,结果wine 不是脚本而是可执行文件。

现在,我不知道这个“过滤器”是否以某种方式编码在程序本身中,或者在默认 wine 安装期间以其他方式指定,所以我不确定这个问题是否更适合 stackoverflow 或超级用户,所以我交叉手指并把它扔到这里。如果我猜错了,我很抱歉。 (另外,我检查了一些类似的问题,但大多数都无关紧要或涉及编辑 shell 配置。)

所以我的问题是,这种“过滤”是如何完成的?提前致谢。

【问题讨论】:

  • 制表符补全是特定于 shell 的,您使用的是哪个 shell (echo $SHELL)
  • 对不起,我正在使用 bash。编辑:4.2.24

标签: linux bash shell tab-completion bash-completion


【解决方案1】:

您可能会在您的系统上找到一个名为/etc/bash_completion 的文件,其中包含设置此行为的函数和complete 命令。该文件将来自您的 shell 启动文件之一,例如 ~/.bashrc。

可能还有一个名为/etc/bash_completion.d 的目录,其中包含具有更多完成功能的单个文件。这些文件来自/etc/bash_completion。

这是我系统上/etc/bash_completion 中的wine 完成命令的样子:

complete -f -X '!*.@(exe|EXE|com|COM|scr|SCR|exe.so)' wine

这组文件大部分由Bash Completion Project维护。

【讨论】:

  • 我确实有这些文件以及你提到的那一行。感谢您的全面回答:-)
【解决方案2】:

您可以查看 bash 手册中的 Programmable Completion 以了解其工作原理。

【讨论】:

  • 请确保它与 ZSH 用户兼容!本指南简单明了,便于理解完成通常是如何实现的:linux-mag.com/id/1106
【解决方案3】:

我知道这是旧的,但我希望用我自己的脚本做类似的事情。

你可以试一试我在这里做的一个例子: http://runnable.com/Uug-FAUPXc4hAADF/autocomplete-for-bash

上面粘贴的代码:

# Create function that will run when a certain phrase is typed in terminal
# and tab key is pressed twice
_math_complete()
{
    # fill local variable with a list of completions
    local COMPLETES="add sub mult div"
    # you can fill this variable however you want. example:
    # ./genMathArgs.sh > ./mathArgsList
    # local COMPLETES=`cat ./mathArgsList`

    # we put the completions into $COMPREPLY using compgen
    COMPREPLY=( $(compgen -W "$COMPLETES" -- ${COMP_WORDS[COMP_CWORD]}) )
    return 0
}

# get completions for command 'math' from function '_math_complete()'
complete -F _math_complete math 

# print instructions
echo ""
echo "To test auto complete do the following:"
echo "Type math then press tab twice." 
echo "You will see the list we created in COMPLETES"
echo ""

【讨论】:

  • 感谢这个清晰的例子。我喜欢使用虚构的命令来演示这个概念的想法。我用它来开发和自动完成zlogin。
猜你喜欢
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多