Linux: Bash Completion

From Define Wiki
Jump to navigation Jump to search

Bash Completion

Hitting the tab to see available options can make life a lot easier. To add a new command to it you need to create the relevent file in /etc/bash_completion.d/ and then update the completions.

Create a competion file for a command

Below is an example file for the command foo. It has to options show and configure. Each of these then have sub options.

_foo()
{
    local cur prev

    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}

    case ${COMP_CWORD} in
        1)
            COMPREPLY=($(compgen -W "configure show" ${cur}))
            ;;
        2)
            case ${prev} in
                configure)
                    COMPREPLY=($(compgen -W "CM DSP NPU" ${cur}))
                    ;;
                show)
                    COMPREPLY=($(compgen -W "some other args" ${cur}))
                    ;;
            esac
            ;;
        *)
            COMPREPLY=()
            ;;
    esac
}

complete -F _foo foo

Source the completion file to update

source /etc/bash_completion