Rég*_* B. 38 command-line autocomplete command-line-arguments
在bash中,mplayer和imagemagick的"convert"等可执行文件在其命令行参数上具有很酷的自动完成功能.例如,如果我输入
mplayer <tab><tab>
Run Code Online (Sandbox Code Playgroud)
在我的一个视频文件夹中,然后mplayer将列出位于该文件夹中的所有媒体文件,并且仅列出媒体文件.
同样,如果我输入
convert -<tab><tab>
Run Code Online (Sandbox Code Playgroud)
然后我将看到转换脚本的所有可能选项,这很棒.
我的问题是如何使用bash,ruby或python脚本实现类似的功能?
hoj*_*ram 10
在已接受的答案中编写您自己的扩展的链接已经失效。引用自http://web.archive.org/web/20090409201619/http://ifacethoughts.net/2009/04/06/extending-bash-auto-completion/
Bash 为您提供了一种指定关键字的方法,并使用它们为您的应用程序自动完成命令行参数。我使用 vim 作为 wiki、任务管理器和联系人。vim helptags 系统让我索引内容而不是搜索它,并且速度显示它。我想添加的一项功能是从 vim 外部访问这些标签。
这可以通过直接的方式完成:
Run Code Online (Sandbox Code Playgroud)$ vim -t tagname
这会将我直接带到使用此标签标记的特定内容。但是,如果我可以为标签提供自动完成功能,这将更有效率。
我首先为 vim 命令行定义了一个 Bash 函数。我将以下代码添加到我的 .bashrc 文件中:
Run Code Online (Sandbox Code Playgroud)function get { vim -t $1 } Now I can use get tagname command to get to the content.
Bash 可编程完成是通过获取 /etc/bash-completion 脚本来完成的。该脚本让我们添加我们的自动完成脚本 /etc/bash-completion.d/ 目录并在调用它时执行它。因此,我在该目录中添加了一个名为 get 的脚本文件,其中包含以下代码。
Run Code Online (Sandbox Code Playgroud)_get() { local cur COMPREPLY=() #Variable to hold the current word cur="${COMP_WORDS[COMP_CWORD]}" #Build a list of our keywords for auto-completion using #the tags file local tags=$(for t in `cat /home/anadgouda/wiki/tags | \ awk '{print $1}'`; do echo ${t}; done) #Generate possible matches and store them in the #array variable COMPREPLY COMPREPLY=($(compgen -W "${tags}" $cur)) } #Assign the auto-completion function _get for our command get. complete -F _get get Once the /etc/bash-completion is sourced, you will get auto-completion for the tags when you use the get command.
连同我的 wiki,我将它用于所有文档工作,有时也用于代码。我还使用从我的代码创建的标签文件。索引系统让我记住上下文而不是文件名和目录。
您可以针对您使用的任何工具调整此系统。您需要做的就是获取命令的关键字列表,并将其提供给 Bash 可编程完成系统。