0

I'm learning about bash completion. Here is my code:

_foo()
{
       local cur prev opts
               COMPREPLY=()
               cur="${COMP_WORDS[COMP_CWORD]}"
               prev="${COMP_WORDS[COMP_CWORD-1]}"
               opts="push pull"
                    case "${prev}" in
                        push)
                            COMPREPLY=( $(compgen -W "--file --key" -- ${cur}) )
                            return 0
                            ;;
                        pull)
                            COMPREPLY=( $(compgen -W "--data --url" -- ${cur}) )
                            return 0
                            ;;
                        esac
      if [[ $COMP_CWORD == 1 ]] ; then
          COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
      fi
              return 0
}
complete -o default -F _foo foo

I want to know, How to pop item from array after it's used? Let me explain with example. This code work as follow:

$ foo [TAB]
$ foo pu [TAB]
push pull
$ foo push [TAB]
$ foo push -- [TAB]
--file --key
$ foo push --file [TAB]
content of PWD

Since I used --file as argument, Next time it should not be shown as available arguments. It means if I do like this

$ foo push --file file.txt [TAB]
--key ##It should be display as output

can anyone tell me, How can I do this? Thanks.

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
rishi kant
  • 1,235
  • 1
  • 9
  • 28

1 Answers1

2

There's no elegant solution; you need to iterate over the list of keys to remove and replace it with an empty string. The new array is created by not quoting the old array expansion, which ordinarily would cause some concern, except the original was created by not quoting the compgen command substitution, so it's OK.

for x in ${COMPWORDS[@]}; do
  COMPREPLY=( ${COMPREPLY[@]//$x} )
done

This removes anything in the list of current words in the command from the possible substitutions. One caveat: if two words share a common prefix, you might partially delete the longer word when removing the shorter.

chepner
  • 497,756
  • 71
  • 530
  • 681