【问题标题】:Git branch in the prompt提示中的 Git 分支
【发布时间】:2017-08-30 19:34:37
【问题描述】:

谁能解释为什么分支名称没有出现在我的 (bash) 提示符上?
我正在使用 ubuntu 16.10。我尝试使用此site 中的说明。

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

我的.bashrc 文件在这里:https://github.com/JeremieGauthier/.bashrc/blob/master/.bashrc

我也尝试了以下代码,但也没有用。

function color_my_prompt {
    local __user_and_host="\[\033[01;32m\]\u@\h"
    local __cur_location="\[\033[01;34m\]\w"
    local __git_branch_color="\[\033[31m\]"
    #local __git_branch="\`ruby -e \"print (%x{git branch 2> /dev/null}.grep(/^\*/).first || '').gsub(/^\* (.+)$/, '(\1) ')\"\`"
    local __git_branch='`git branch 2> /dev/null | grep -e ^* | sed -E  s/^\\\\\*\ \(.+\)$/\(\\\\\1\)\ /`'
    local __prompt_tail="\[\033[35m\]$"
    local __last_color="\[\033[00m\]"
    export PS1="$__user_and_host $__cur_location $__git_branch_color$__git_branch$__prompt_tail$__last_color "
}
color_my_prompt

【问题讨论】:

  • 而不是git branch(这是一个瓷器命令),您应该使用get rev-parse --abbrev-ref HEAD 来获取分支名称。如果您停止丢弃错误消息,您可能会看到您可能不在 git 工作目录中,因此parse_git_branch 不会生成任何输出。

标签: bash rc


【解决方案1】:

在安装时git 带有一个git-prompt.sh 那个bash 函数__git_ps1 来更新提示。

这个功能很简单,当你在一个git repo目录中cd时添加当前分支。

只需添加对该函数或ps1 中可用的另一个函数的调用,并确保您的.bashrc.bash_profile 加载bash_completion 目录。

如果您的 git 版本不包含 git_prompt.sh 脚本,请手动下载它并按照它提供的说明进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2012-08-29
    • 1970-01-01
    相关资源
    最近更新 更多