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
)
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).
The recommended method is by using __git_complete()
:
__git_complete gitpull _git_pull
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With