简体   繁体   English

基于第一个值的不同选项的 bash 完成

[英]bash completion with different options based on first value

I'm currently trying to write a bash_completion script for one of our tools.我目前正在尝试为我们的一个工具编写一个 bash_completion 脚本。 Was looking at the apt-get and chkconfig scripts for some help.正在查看 apt-get 和 chkconfig 脚本以寻求帮助。 Basically what I want to do is get a different option selection based on the first value.基本上我想做的是根据第一个值获得不同的选项选择。 There can be more than one option to a value.一个值可以有多个选项。

command <value1> <--option1> <--option2> ...
command <value2> <--option3> <--option4> ...

Looking at the apt-get script, it will return the same list of options for any first value.查看 apt-get 脚本,它将为任何第一个值返回相同的选项列表。 So this is not what I need.所以这不是我需要的。

Here is what I got so far:这是我到目前为止所得到的:

 _supdeploy()
{
    local cur prev opts cword
    _init_completion || return

    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="deploy destroy supported list fulllist status fullstatus getip shutdown powerOff powerOn"

    case "${prev}" in
        deploy)
           if [[ "$cur" == -* ]]; then
               if [[ $cword -eq 2 || $cword -eq 3 || $cword -eq 4 ]]; then
                   COMPREPLY=( $( compgen -W '--hostname --os --version' -- "$cur" ) )
               fi
           fi
           return 0
           ;;
        destroy)
            if [[ "$cur" == -* ]]; then
               COMPREPLY=( $( compgen -W '--name --silent' -- "$cur" ) )
            fi
            return 0
            ;;
        *)
            COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
            return 0
            ;;
    esac

} &&
complete -F _supdeploy supdeploy

I get a different selection of options for both deploy and destroy.我得到了不同的部署和销毁选项选择。 But I can only use one -- option.但我只能使用一个--选项。 When I try to use -- again, nothing happens, and without the -- I get the list from opts.当我再次尝试使用--时,没有任何反应,如果没有--我从 opts 中获得列表。

It is probably something easy, but I can't find the error here at the moment.这可能很简单,但我现在在这里找不到错误。 I also have it tried without the $cword before, same result我之前也试过没有$cword ,结果相同

Instead of prev , you just want to look at the value of the first argument each time:而不是prev ,您只想每次查看第一个参数的值:

case ${COMP_WORDS[1]} of

It gets a little tricker if you allow "general" options to precede the subcommand, but in general you want to look at the first non-option argument, not necessarily the previous argument.如果您允许“通用”选项位于子命令之前,它会变得有点棘手,但通常您想查看第一个非选项参数,而不一定是前一个参数。

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

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