Git autocomplete for custom bash functions

In mine .bash_profile, I have many functional shortcuts for git. For instance:

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 type this in the terminal, I want it to autofill the git branches. How should I do it? (I already use .git-completion.bash)

+5
source share
2 answers

Manually executing bash is just as simple:

# 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 searching for the above commands:

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

The final link to bash termination is (of course) the "Programmable Termination" section of the bash manual, but a nice introduction is provided on the Debian Administration page ( part 1 and more important part 2 ).

+5

- __git_complete():

__git_complete gitpull _git_pull
0

Source: https://habr.com/ru/post/1687332/


All Articles