繁体   English   中英

在shell中自定义选项卡完成

[英]Customize tab completion in shell

这可能比“自定义标签完成”有更好的名称,但这是场景:

通常,当我在命令行并输入命令,然后输入{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

想这可能是某种负责过滤包装脚本的,一个做了whichfile的事实证明wine是没有剧本的,但一个可执行文件。

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

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

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

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

这是wine completion命令从我的系统上的/etc/bash_completion看起来的样子:

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

这组文件在很大程度上由Bash完成项目维护。

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

我知道这已经过时了,但我正在寻找与我自己的剧本类似的东西。

你可以玩我在这里做的一个例子: 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 ""

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM