在我的 .bash_profile
中,我有很多 git 的功能快捷方式。例如:
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;
}
但是,当我在终端中输入这个时,我希望它自动完成 git 分支。我该怎么做呢? (我已经在使用 .git-completion.bash
)
最佳答案
手工制作的 bash 补全就这么简单:
# 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
获取上述命令后:
$ gitpull <TAB>
asd master qwe zxc
$ gitpull m<TAB>
$ gitpull master
关于 bash 完成的最终引用(当然)是关于 Programmable Completion 的部分在 bash 手册中,但在“Debian 管理”页面(part 1 和更重要的 part 2)上给出了一个很好的介绍。
关于自定义 bash 函数的 Git 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46696156/