0

I am new to compgen and want to use it for a script I am working on. This script can have "commands" and "options" as arguments like so:

script add "value"
script --path "/a/file/path" add "value"
# and others

I wrote a completion script that looks like that:

_script_completions() {
    arg_index="${COMP_CWORD}"
    if [[ "${arg_index}" -eq 1 ]]; then
        COMPREPLY=($(compgen -W "--path add" "${COMP_WORDS[1]}"))
    fi
}
complete -F _script_completions script

This script is working fine for the "add" command but fails on the "--path" option. For example: When I enter:

$ script --p<TAB>

I get:

$ ./script --pbash: compgen: --: invalid option
compgen: usage: compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist]  [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]

How do I add the completion for my own script options correctly?

TimFinnegan
  • 583
  • 5
  • 17

1 Answers1

6

With compgen -W "--path add" "${COMP_WORDS[1]}" and script --p<tab> the last argument ${COMP_WORDS[1]} turns into --p and is then interpreted as an option for compgen instead of the word to complete. You can use the argument -- to mark the end of options:

_script_completions() {
    arg_index="${COMP_CWORD}"
    if [[ "${arg_index}" -eq 1 ]]; then
        COMPREPLY=($(compgen -W "--path add" -- "${COMP_WORDS[1]}"))
    fi
}
complete -F _script_completions script
Socowi
  • 25,550
  • 3
  • 32
  • 54