Search code examples
gitbashbash-completion

Git autocomplete for custom bash functions


In my .bash_profile, I have a lot of functional shortcuts for git. For example:

function gitpull() {
    branch="$1"

    if [[ -z $branch ]]; then
        current_branch=`git symbolic-ref -q --short HEAD`
        git pull origin $current_branch;
    elif [[ -n $branch && $branch == "m" ]]; then
        git pull origin master;
    else
        git pull origin $branch;
    fi;
}

However, when I'm typing this in the terminal, I want it to autocomplete git branches. How do I do this? (I already am using .git-completion.bash)


Solution

  • Manually-crafted bash completion is as simple as this:

    # our handler that returns choices by populating Bash array COMPREPLY
    # (filtered by the currently entered word ($2) via compgen builtin)
    _gitpull_complete() {
        branches=$(git branch -l | cut -c3-)
        COMPREPLY=($(compgen -W "$branches" -- "$2"))
    }
    
    # we now register our handler to provide completion hints for the "gitpull" command
    complete -F _gitpull_complete gitpull
    

    After sourcing the above commands:

    $ gitpull <TAB>
    asd     master  qwe     zxc
    $ gitpull m<TAB>
    $ gitpull master
    

    The ultimate reference on bash completion is (of course) the section on Programmable Completion in the bash manual, but a nice introduction is given on "Debian Administration" page (part 1 and a more important part 2).