5

I am trying to make autocomplete work and wroted a piece of code to demonstrate an issue I faced up:

$ cat completion.sh
function _completion_command() {
    compopt +o bashdefault +o default +o dirnames +o filenames +o nospace +o plusdirs
    local cur=${COMP_WORDS[COMP_CWORD]}
    local prev=${COMP_WORDS[COMP_CWORD-1]}
    case "$prev" in
        -u)
            compopt -o nospace
            COMPREPLY=($(compgen -S\= -W "parm" -- $cur))
            return 0
            ;;
         parm)
            COMPREPLY=($(compgen  -W "a b c" -- $cur))
            return 0
            ;;
    esac
    COMPREPLY=($(compgen  -W "-u" -- $cur))
    return 0
}
complete -F _completion_command command

I expected autocompletion offers me possible arguments for parameter named "parm":

. completion.sh
./command -u parm=

Tab Tab

a b c

But in my case autocomplete offers me nothing.

2

prev contains parm
cur contains =
compgen -W "a b c" -- = outputs nothing

You can use _get_comp_words_by_ref from bash-completion:

source bash-completion # /usr/share/bash-completion/bash_completion on Ubuntu with bash-complete installed

function _completion_command() {
  local cur prev
  _get_comp_words_by_ref -n = cur prev
  case "$prev" in
    -u)
      case "$cur" in
        parm=*)
          COMPREPLY=($(compgen -W "a b c" -- ${cur#*=}))
          return 0;
          ;;
        *)
          compopt -o nospace
          COMPREPLY=($(compgen -S\= -W "parm" -- $cur))
          return 0;
          ;;
      esac
      ;;
  esac

  COMPREPLY=($(compgen  -W "-u" -- $cur))
}

complete -F _completion_command command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.