Bash 完成:允许标记一次

Bash completion: Allow flags once

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

_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?

谢谢

已解决。灵感来自@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
}