Bash完成:允许标志一次

时间:2015-03-10 11:45:40

标签: bash bash-completion

我有一个基本的完整功能:

_my_complete () 
{ 
    local cur prev opts opts2;
    COMPREPLY=();
    cur="${COMP_WORDS[COMP_CWORD]}";
    prev="${COMP_WORDS[COMP_CWORD-1]}";
    opts="foo bar";
    opts2="-f -s";
    case ${COMP_CWORD} in 
        1)
            COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
        ;;
        2 | 4)
            COMPREPLY=($(compgen -W "${opts2}" -- ${cur}))
        ;;
    esac
}

如何在命令行中限制完成只接受-f或-s一次?

由于

1 个答案:

答案 0 :(得分:1)

解决。灵感来自@whjm和post

的评论
_my_complete() {
        local cur prev opts opts2 subopts ;
        COMPREPLY=();
        cur="${COMP_WORDS[COMP_CWORD]}";
        prev="${COMP_WORDS[COMP_CWORD-1]}";
        opts="foo bar";
        opts2="-f -s";
        subopts=();

        for i in ${opts2}
        do
                for j in "${COMP_WORDS[@]}"
                do
                        if [[ "$i" == "$j" ]] 
                        then
                                continue 2
                        fi
                done
                subopts+=("$i")
        done  

        case ${COMP_CWORD} in
            1)
                    COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
                    ;;
            2|4)
                    COMPREPLY=($(compgen -W "${subopts[*]}" -- ${cur}))
                    ;;
        esac
}