6

I am trying to make Bash autocomplete work and wrote this piece of code to demonstrate an issue I faced:

$ 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 completion to offer me possible arguments for the parameter named "parm":

. completion.sh
./command -u parm=

Tab Tab

a b c

But in my case autocomplete offers me nothing.

1 Answer 1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .