2017-10-11 39 views
4

在我的.bash_profile中,我有很多git的功能快捷方式。例如:自定义bash函数的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分支。我该怎么做呢? (I已经正在使用.git-completion.bash

回答

3

手动制作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)上给出了一个很好的介绍。

+1

但不自动完成它。如果我输入'gitpull mas ',它不会像它应该那样完成'master'。 – Nxt3

+1

你说得对,对不起,我们需要根据当前(前缀)词用'compgen'过滤选项。 – randomir

+2

这太棒了。非常感谢! – Nxt3