自定义 bash 函数的 Git 自动完成

标签 git bash bash-completion

在我的 .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/

相关文章:

regex - 使用字符串替换取消注释基于正则表达式的配置行

bash - 如果用户错误地调用脚本,使 Bash 脚本退出并打印错误消息

bash-completion - bash_completion 的不同目录(自动完成指定目录下的子文件夹)

command-line-arguments - 如何使用给定的参数集完成 GNU 长选项?

python - 在 python 脚本中运行 “git clone https://remote.git” 时如何提供密码(有 @ )?

git - 用于访问多个存储库的 SSH 配置不起作用

bash - '$?' 在 bash 脚本中意味着什么?

bash - 如何使用即时定义的 bash 完成函数?

git - 在确定是否可以删除分支时,我可以让 git 更聪明吗?

linux - Kieran Healy 在 Linux (fedora19) 中的 emacs 入门工具包 : "/bin/bash: osascript: command not found" message