Search code examples
bashshellbash-completioncompgen

How to use bash `compgen` with my own script options?


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?


Solution

  • 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