【问题标题】:Customizing bash prompt (PS1) for git branches with colors使用颜色为 git 分支自定义 bash 提示符 (PS1)
【发布时间】:2014-04-01 17:17:35
【问题描述】:

我目前正在使用git-prompt.sh 自定义我的 bash 提示符 (PS1) 以在我的 bash 提示符中显示我的 git repo 的状态。

This stackoverflow answer 很有帮助,但不是我想要的。

我当前的.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) 的颜色

谢谢一百万!

【问题讨论】:

  • 您可能需要编写可以在提示配置中调用的脚本和函数才能做到这一点。
  • 我最终自定义了 git-prompt.sh 文件。这就是我的结果。 github.com/AJ-Acevedo/dotfiles/commit/…

标签: git bash shell


【解决方案1】:

我今天想要一个类似的功能,我通过如下修改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】:

    我从一篇关于自定义提示的文章中找到了这个 sn-p。 这并不完全是您正在寻找的,但只需要一些小的修改。 有一些颜色在这个sn-p中没有定义但是可以找到here

    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

    【讨论】:

    • 我会把这个作为答案,因为它完全提供了实现我所寻找的资源。我还偶然发现了github.com/magicmonty/bash-git-prompt,我要去看看。谢谢!
    • 你的颜色sn-p的url已经没有了。
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2013-03-30
    • 2020-12-16
    • 2020-11-07
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多