Bash – How to tell bash valid tab-completions for arguments to the Python script

autocompletebash

Say I have a program hello.py and one possible valid argument to it is:

./hello.py autoawesomesauce

Is is possible to type in:

./hello.py auto[tab]

at which point the partially completed argument is sent to hello, which recognizes it as such and then completes it on the shell to:

./hello.py autoawesomesauce

I know git does something like this, but can it be done for a Python script + Bash?

Best Answer

On Linux systems, you can generally find a large number of example scripts under: /etc/bash_completion.d. If you source these scripts, then you will get the autocomplete behavior.

I've included an example from that directory. This is the completion script for unrar.

_unrar()
{
    local cur

    COMPREPLY=()
    _get_comp_words_by_ref cur

    if [[ "$cur" == -* ]] ; then
        COMPREPLY=( $( compgen -W '-ad -ap -av- -c- -cfg- -cl -cu \
            -dh -ep -f -idp -ierr -inul -kb -o+ -o- -ow -p -p- -r -ta \
            -tb -tn -to -u -v -ver -vp -x -x@ -y' -- "$cur" ) )
    else
        if [ $COMP_CWORD -eq 1 ]; then
            COMPREPLY=( $( compgen -W 'e l lb lt p t v vb vt x' -- "$cur" ) )
        else
            _filedir '@(rar|RAR)'
        fi
    fi

} &&
complete -F _unrar -o filenames unrar
Related Question