自定义PS1提示有时会导致行被覆盖



我的PS1设置有问题,我设置它是为了显示git存储库分支和状态。

有时我对终端中被覆盖的线路有问题。我不知道为什么。如果我设置PS1="$ ",它可以正常工作。事实上,下面的设置在我的另一款macOS Catalina/Terminal.app/bash.的macbook pro上运行得很好

#!/bin/bash -e
function init {
case $OSTYPE in
linux*)
MAGENTA='e[0;31m'
GREEN='e[0;32m'
ORANGE='e[1;33m'
BLUE='e[0;34m'
PURPLE='e[0;35m'
WHITE='e[0;37m'
RESET='e[0m'
;;
darwin*)
MAGENTA="33[1;31m"
GREEN="33[1;32m"
ORANGE="33[1;33m"
BLUE="33[1;34m"
PURPLE="33[1;35m"
WHITE="33[1;37m"
RESET="33[m"
;;
esac
}
init
function git_color {
local git_status="$(git status 2> /dev/null)"
if [[ ! $git_status =~ "working directory clean" ]]; then
echo -e $MAGENTA
elif [[ $git_status =~ "Your branch is ahead of" ]]; then
echo -e $ORANGE
elif [[ $git_status =~ "nothing to commit" ]]; then
echo -e $GREEN
else
echo -e $PURPLE
fi
}
function git_branch {
local git_status="$(git status 2> /dev/null)"
local on_branch="On branch ([^${IFS}]*)"
local on_branch_zh="位于分支 ([^${IFS}]*)"
local on_commit="HEAD detached at ([^${IFS}]*)"
if [[ $git_status =~ $on_branch ]]; then
local branch=${BASH_REMATCH[1]}
echo "($branch)"
elif [[ $git_status =~ $on_branch_zh ]]; then
local branch=${BASH_REMATCH[1]}
echo "($branch)"
elif [[ $git_status =~ $on_commit ]]; then
local commit=${BASH_REMATCH[1]}
echo "($commit)"
fi
}
#export PS1="[${PURPLE}]u[$GREEN]@[$ORANGE]h [$BLUE]w $(git_color)$(git_branch)[$RESET] [$GREEN]$[$RESET] "
export PS1="[$PURPLE]u[$GREEN]@[$ORANGE]kn [$BLUE]W [$(git_color)][$(git_branch)] [$GREEN]$[$RESET] "
export PS2="[$ORANGE]→ [$RESET]"

[]应该只围绕非打印字符,这样bash就知道哪些序列会移动光标,哪些不会。不正确地使用它们可能会导致bash丢失对光标位置的跟踪,并错误地刷新终端。

您在所有的颜色代码周围都有它——这是正确的——但不应该在$(git_branch)周围有它,因为它打印可见的文本。

[$(git_branch)]
^^              ^^

最新更新