如何自动完成嵌套的多级子命令? [英] How do I autocomplete nested, multi-level subcommands?
问题描述
我正在尝试为自己的命令集开发自动完成功能或制表符完成功能.
I am trying to develop an autocomplete or tab-complete feature for my own set of commands.
例如,假设foo是我的二进制文件:
For example, assume foo is my binary:
CLI>> foo [TAB] [TAB]
它应该显示主要命令configure
和show
.
It should show the main commands configure
and show
.
然后,如果我选择configure
,它将显示子命令CM
,DSP
和NPU
:
Then if I select configure
, it should show the subcommands CM
, DSP
and NPU
:
CLI>> foo configure [TAB] [TAB]
DSP NPU CM`
我只知道如何制表和完成并显示第一级-如何获得第二级?
I only know how to tab-complete and display for the first level - how can I get the second level as well?
我将其放置在/etc/completion.d
中.
我的代码:
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
words=("${COMP_WORDS[@]}")
cword=$COMP_CWORD
opts="configure show"
}
我对如何在configure
下添加子命令CM
DSP
NPU
感到困惑.
I'm stuck as how to add sub commands CM
DSP
NPU
under configure
.
推荐答案
以下是您的两级案例的示例脚本(其中show
的子命令部分显示了如何完成-您只需删除这三行如果它们与您的情况不相关):
Here's an example script for your two-level case (with a section for subcommands of show
to show how it's done - you can just delete those three lines if they're not relevant to your case):
_foo()
{
local cur prev
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
case ${COMP_CWORD} in
1)
COMPREPLY=($(compgen -W "configure show" -- ${cur}))
;;
2)
case ${prev} in
configure)
COMPREPLY=($(compgen -W "CM DSP NPU" -- ${cur}))
;;
show)
COMPREPLY=($(compgen -W "some other args" -- ${cur}))
;;
esac
;;
*)
COMPREPLY=()
;;
esac
}
complete -F _foo foo
希望从该示例中可以很明显地看出,如何将其扩展到三级命令等.
Hopefully it's fairly obvious from that example how you'd extend it to three-level commands etc., as well.
这篇关于如何自动完成嵌套的多级子命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!