Maxim_united
Maxim_united

Reputation: 2003

Bash completion: Allow flags once

I have a basic complete function:

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

How can limit the completion to accept the -f or the -s only once in the command line?

Thanks

Upvotes: 4

Views: 494

Answers (1)

Maxim_united
Maxim_united

Reputation: 2003

Solved. Inspired by comment of @whjm and this 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
}

Upvotes: 2

Related Questions