我希望“▸”的背景颜色根据最后部分的颜色而改变。因此,如果我不在git repo中,它应该是蓝色,但是当我在git repo中时,黄色。
这是我的.bash_profile
中的PS1的样子
# 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使用的是子外壳,因此无法使用。
答案 0 :(得分:1)
好吧,您的__git_info
函数返回一个状态,那么为什么不使用它呢? (确保ARE是git repo时,确保它返回NON-零。)不要重置函数中的颜色,而是允许它们保持原样并在箭头之后重置它们:
function __dir() {
printf '\[\e[1;97;44m\] \w ';
}
function __git_status() {
local info=$(__git_info)
[ $? -ne 0 ] && printf "\[\e[30;43m\]$info";
}
function __arrow() {
printf ' ▸ \[\e[0m\]';
}
export PS1="$(__host)$(__dir)$(__git_status)$(__arrow) "