愚蠢的周六早上代码片段。
我在网上找到了一个片段代码,可以让我获取 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) $ "
关于git - Bash - 用于分支管理的 GIT 小片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908950/