git - Bash - 用于分支管理的 GIT 小片段

标签 git bash ps1

愚蠢的周六早上代码片段。

我在网上找到了一个片段代码,可以让我获取 PS1 中的当前分支,太棒了!但是...

我希望根据分支有不同的颜色。

我说,“你对 bash 一无所知,但应该很简单!只是一个 if...”

经过 6 个小时的测试,我们开始了。

有人可以解释一下问题出在哪里吗?

我知道 GitHub 上有很多项目可以为我完成这项工作,但我只想了解一下。

非常感谢

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'

}

set_ps1_git_branch_color(){
    BRANCH=$(parse_git_branch)
    if [ $BRANCH == "(master)" ]; then
        echo -e "\W\[\033[35m\] $BRANCH \[\033[00m\]"
    fi
    if [ $BRANCH == "(test)" ]; then
        echo -e "\W\[\033[32m\] $BRANCH \[\033[00m\]"
    fi         
}
export PS1="\u@\h $(set_ps1_git_branch_color) $ "

只要我在每次 git 操作(如 checkout )后执行 source ~/.bash_profile ,它就可以工作。

但是原始代码段 parse_git_branch() 无需使用 source 命令即可更改分支名称。

那么...我在这里缺少什么? :(

最佳答案

您的错误很少:

 export PS1="\u@\h $(set_ps1_git_branch_color) $ "

 # should be (added \ before $(set...))
 # the \ will execute the command during runtime and not right now.
 # without the \ it will executed and determined of first run and not every time
 export PS1="\u@\h \$(set_ps1_git_branch_color) $ "

颜色格式:

# Output colors
red='\033[0;31m';
green='\033[0;32m';
yellow='\033[0;33m';
default='\033[0;m';

使用颜色更新脚本:

set_ps1_git_branch_color(){
    ...
    echo -e "${green} $BRANCH ${default}"
}

修复了复制和粘贴的脚本

# Output colors
red='\033[0;31m';
green='\033[0;32m';
yellow='\033[0;33m';
default='\033[0;m';

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'

}

set_ps1_git_branch_color(){
    BRANCH=$(parse_git_branch)
    if [ $BRANCH == "(master)" ]; then
        echo -e "${green} $BRANCH ${default}"
    fi
    if [ $BRANCH == "(test)" ]; then
        echo -e "${yellow} $BRANCH ${default}"
    fi
}

export PS1="\u@\h \$(set_ps1_git_branch_color) $ "

enter image description here

关于git - Bash - 用于分支管理的 GIT 小片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908950/

相关文章:

使用 GitPython 的 git archive --remote 命令

Xcode 5 - 如何在工作区中使用源代码管理

linux - 查找由另一台服务器远程触发的进程

linux - 我们如何在 bash 中使用 for 循环将日期列表转换为 yyyymmdd 格式

bash - 使用管道和 bash 命令查找模式

git - 错误: RPC failed; HTTP 502 curl 22 The requested URL returned error: 502 Bad Gateway fatal

git - 有没有办法在 AWS CodeCommit 中获取文件的原始 URL?

macos - (Mac) -bash : __git_ps1: command not found

shell - 如何修改 PS1 以在最右角显示时间?

Bash $PS1 麻烦(ubuntu)