使用颜色自定义git分支的bash提示符(PS1)

3
我目前正在使用git-prompt.sh来自定义我的bash提示符(PS1),以在我的bash提示符中显示我git repo的状态。 这个stackoverflow答案非常有帮助,但不完全是我所寻找的。
我的当前.bashrc看起来像这样:
[aj@computer-name my_current_working_directory (git-branch-name)]$

我的 .gitconfig 使用以下内容:

[color "status"]
  added = green
  changed = yellow
  untracked = red

问题是,我如何实现以下内容? 我希望我的bash提示继续以上面的方式显示,但根据我在.gitconfig中设置的状态颜色更改(git-branch-name)的颜色。 非常感谢!

1
你可能需要编写脚本和函数,以便在提示符配置中调用它们来完成这个任务。 - user456814
我最终定制了git-prompt.sh文件。这是我的最终结果。https://github.com/AJ-Acevedo/dotfiles/commit/7ce6466aaf5beda52e42af566a7252924dddde99 - AJ.
2个回答

4

今天我想要一个类似的功能,通过修改git-prompt.sh文件我实现了它:

__git_ps1_colorize_gitstring ()
{
    if [[ -n ${ZSH_VERSION-} ]]; then
        local c_red='%F{red}'
        local c_green='%F{green}'
        local c_clear='%f'
    else
        local c_red='\[\e[31m\]'
        local c_green='\[\e[32m\]'
        local c_clear='\[\e[0m\]'
    fi

    local branch_color=""
    if [ "$w" = "*" ]; then  # modified
        branch_color="$c_red"
    elif  [ -n "$u" ]; then  # untracked
        branch_color="$c_red"
    elif [ -n "$i" ]; then
        branch_color="$c_green"
    else
        branch_color="$c_clear"
    fi

    c="$branch_color$c"
    z="$c_clear$z"
    w=""
    i=""
    s=""
    u=""
    r="$c_clear$r" 
}

我将以下内容添加到我的.bashrc文件中:

GIT_PS1_SHOWDIRTYSTATE=1
GIT_PS1_SHOWUNTRACKEDFILES=1
GIT_PS1_SHOWCOLORHINTS=1

这将改变我的分支名称的颜色,而无需将*%=字符串添加到提示符中。

2

我在一篇关于自定义提示符的文章中找到了这个代码片段。虽然不完全符合你的要求,但只需要进行一些小的修改即可。此代码片段中未定义的一些颜色可以在这里找到。

export PS1=$IBlack$Time12h$Color_Off'$(git branch &>/dev/null;\
if [ $? -eq 0 ]; then \
  echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \
if [ "$?" -eq "0" ]; then \
  # @4 - Clean repository - nothing to commit
  echo "'$Green'"$(__git_ps1 " (%s)"); \
else \
  # @5 - Changes to working tree
  echo "'$IRed'"$(__git_ps1 " {%s}"); \
fi) '$BYellow$PathShort$Color_Off'\$ "; \
else \
  # @2 - Prompt when not in GIT repo
echo " '$Yellow$PathShort$Color_Off'\$ "; \
fi)'

这里还有一个链接,列出了提示符的自定义列表。

http://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html


1
我会接受这个答案,因为它完全给了我实现我所寻找的资源。我还偶然发现了 https://github.com/magicmonty/bash-git-prompt,我打算去看看。谢谢! - AJ.
你的颜色代码片段的URL已经失效了。 - Faust

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接