Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Last active August 15, 2018 11:07
Show Gist options
  • Save bdelespierre/990fbb938b2c0e4229fc65de76a40119 to your computer and use it in GitHub Desktop.
Save bdelespierre/990fbb938b2c0e4229fc65de76a40119 to your computer and use it in GitHub Desktop.

Static Auto-completion

Create a file in:

/etc/bash_completion.d/foo

With the following content:

_foo() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--help --verbose --version"

    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _foo foo
  • COMP_WORDS is an array containing all individual words in the current command line.
  • COMP_CWORD is an index of the word containing the current cursor position.
  • COMPREPLY is an array variable from which Bash reads the possible completions.

And the compgen command returns the array of elements from --help, --verbose and --version matching the current word "${cur}":

compgen -W "--help --verbose --version" -- "<userinput>"

See orignal post, source

Programmable Auto-completion

Have look at /etc/bash_completion and /etc/bash_completion.d/* for some examples.

See GNU's manual

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment