Shell 端子颜色导致提示跳回到行的开头

Shell 端子颜色导致提示跳回到行的开头,shell,command-line,colors,terminal,prompt,Shell,Command Line,Colors,Terminal,Prompt,在使用git时,我决定将其添加到.bashrc文件中。此文件向我显示当前正在处理的分支的名称。 我还决定添加一些颜色 if [ -f ~/.git-prompt.sh ]; then #include the branch detection file source ~/.git-prompt.sh #add the current branch in yellow export PS1='$(__git_ps1 "[\e[38;5;220m%s\x1b[0m

在使用git时,我决定将其添加到.bashrc文件中。此文件向我显示当前正在处理的分支的名称。 我还决定添加一些颜色

if [ -f ~/.git-prompt.sh ]; then

    #include the branch detection file
    source ~/.git-prompt.sh

    #add the current branch in yellow
    export PS1='$(__git_ps1 "[\e[38;5;220m%s\x1b[0m]")'

    #make the rest of the text in the prompt gray
    PS1+="\e[38;5;245m\w$ "

    #set colors back to default
    PS1+="\033[0m"
fi
使用任何终端(gnome终端、xterm、QUEK)都会导致相同的问题。当打印出来的行太长时

提示跳回到行的开头。这可能是因为彩色文本的实际长度要长得多


我怎样才能在没有这个问题的情况下得到终端颜色呢?

我想你需要写一些东西

#add the current branch in yellow
export PS1='$(__git_ps1 "[\[\e[38;5;220m\]%s\[\x1b[0m\]]")'

#make the rest of the text in the prompt gray
PS1+="\[\e[38;5;245m\]\w$ "

#set colors back to default
PS1+="\[\033[0m\]"

因此,所有颜色指令周围都有
\[
\]

这解决了我的问题,因为现在终端提示符移动正确。