【发布时间】:2019-05-03 03:19:28
【问题描述】:
我正在尝试在终端提示中为当前的 git 分支添加一些颜色。
我的提示:
export PS1="
\e[32m\u@\h \e[36m\w \`parse_git_branch\`
\\e[0m$ "
所以你可能猜到了,它显示的是这样的:
user@host path/to/dir [git branch[ !]]。
[git branch] 仅在当前文件夹是 git 目录时显示。感叹号!仅在当前分支发生变化时才会显示。
所以,我想为 git 分支添加颜色(红色),但前提是它有更改。我不能在提示声明中的parse_git_branch 函数之前添加\e[31m,因为当它们没有更改时,它不给我使用默认颜色的可能性,分支的名称将始终显示在红色。
所以我必须修改函数本身。这里是:
function parse_git_branch() {
BRANCH=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
if [ ! "${BRANCH}" == "" ]
then
STAT=`parse_git_dirty`
echo "[${BRANCH}${STAT}]"
else
echo ""
fi
}
我尝试了很多不同的东西。就像在 echo 语句中的 [${BRANCH}${STAT}] 之前声明颜色 \033[31m 一样。这样做的问题是,和以前一样,没有变化时颜色也会变成红色。
这里是parse_git_dirty 函数:
function parse_git_dirty {
status=`git status 2>&1 | tee`
dirty=`echo -n "${status}" 2> /dev/null | grep "modified:" &> /dev/null; echo "$?"`
untracked=`echo -n "${status}" 2> /dev/null | grep "Untracked files" &> /dev/null; echo "$?"`
ahead=`echo -n "${status}" 2> /dev/null | grep "Your branch is ahead of" &> /dev/null; echo "$?"`
newfile=`echo -n "${status}" 2> /dev/null | grep "new file:" &> /dev/null; echo "$?"`
renamed=`echo -n "${status}" 2> /dev/null | grep "renamed:" &> /dev/null; echo "$?"`
deleted=`echo -n "${status}" 2> /dev/null | grep "deleted:" &> /dev/null; echo "$?"`
bits=''
if [ "${renamed}" == "0" ]; then
bits=">${bits}"
fi
if [ "${ahead}" == "0" ]; then
bits="*${bits}"
fi
if [ "${newfile}" == "0" ]; then
bits="+${bits}"
fi
if [ "${untracked}" == "0" ]; then
bits="?${bits}"
fi
if [ "${deleted}" == "0" ]; then
bits="x${bits}"
fi
if [ "${dirty}" == "0" ]; then
bits="!${bits}"
fi
if [ ! "${bits}" == "" ]; then
echo " ${bits}"
else
echo ""
fi
}
你建议我应该尝试什么?
谢谢。
【问题讨论】: