【发布时间】:2018-07-31 13:35:26
【问题描述】:
我希望“▸”背景颜色根据最后一部分的颜色而改变。所以,如果我不在 git repo 中,它应该是蓝色的,但是当我在 git repo 中时,它应该是黄色的。
这是我的 PS1 在我的.bash_profile 中的样子
# git info on prompt
function __git_info() {
local -r SYMBOL_GIT_BRANCH="⑂";
local -r SYMBOL_GIT_MODIFIED="*";
local -r SYMBOL_GIT_PUSH="↑";
local -r SYMBOL_GIT_PULL="↓";
hash git 2>/dev/null || return 0; # git not found
# current branch reference
local ref=$(git symbolic-ref --short HEAD 2>/dev/null);
# if it's not a normal branch name, get tag name or short unique hash
[[ -z "$ref" ]] && ref=$(git describe --tags --always 2>/dev/null);
[[ -n "$ref" ]] || return 0; #not a git repo
local following; # ahead/behind count
local modified; # whether something has been modified locally
local extras; # additional info
local status; # status of the repo
local untracked; # whether or not there are untracked files
local staged; # whether or not there are staged files
status=$(git status 2>&1 | tee);
untracked=$(printf "%s" "$status" 2> /dev/null | grep -m 1 "Untracked files" &> /dev/null; printf "%s" "$?");
staged=$(printf "%s" "$status" 2> /dev/null | grep -m 1 "Changes to be committed" &> /dev/null; printf "%s" "$?");
[[ "${untracked}" == "0" ]] && extras+="?";
[[ "${staged}" == "0" ]] && extras+="+";
# scan first two lines of output from `git status`
while IFS= read -r line; do
if [[ $line =~ ^## ]]; then #header line
[[ $line =~ ahead\ ([0-9]+) ]] && following+="$SYMBOL_GIT_PUSH${BASH_REMATCH[1]}"
[[ $line =~ behind\ ([0-9]+) ]] && following+="$SYMBOL_GIT_PULL${BASH_REMATCH[1]}"
else #branch is modified if output contains more lines after the header
modified=" $SYMBOL_GIT_MODIFIED";
break;
fi;
done < <(git status --porcelain --branch 2>/dev/null);
# print the git branch segment without a trailing newline
printf "%s" " [$SYMBOL_GIT_BRANCH$following $ref$modified$extras] ";
}
## Prompt customizations ##
function __host() {
printf '\[\e[30;102m\] \h \[\e[0m\]';
}
function __dir() {
printf '\[\e[1;97;44m\] \w \[\e[0m\]';
}
function __git_status() {
printf "\[\e[30;43m\]\$(__git_info)\[\e[0m\]";
}
function __arrow() {
printf '\[\e[1;97;44m\] ▸ \[\e[0m\]';
}
export PS1="$(__host)$(__dir)$(__git_status)$(__arrow) "
有人知道如何实现这一点吗?我尝试设置全局变量,但 PS1 使用的是子外壳,所以这不起作用。
【问题讨论】:
-
你不能从
__git_status()的末尾删除\[\e[0m\]和从__arrow()的开头删除\[\e[1;97;44m\]吗?