为什么我的 bash 提示有时会被覆盖?

u_s*_*345 1 bash prompt

这是我的相关部分bashrc

function find_git_branch {
    local dir=. head
    until [ "$dir" -ef / ]; do
        if [ -f "$dir/.git/HEAD" ]; then
            head=$(< "$dir/.git/HEAD")
            if [[ $head == ref:\ refs/heads/* ]]; then
                git_branch=" (${head#*/*/})"
            elif [[ $head != '' ]]; then
                git_branch=' (detached)'
            else
                git_branch=' (unknown)'
            fi
            return
        fi
        dir="../$dir"
    done
    git_branch=''
}

function shortpath {
#  How many characters of the $PWD should be kept
  local pwd_length=40
  local lpwd="${PWD/#$HOME/~}"
  if [ $(echo -n $lpwd | wc -c | tr -d " ") -gt $pwd_length ]
    then newPWD="...$(echo -n $lpwd | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
    else newPWD="$(echo -n $lpwd)"
  fi
  echo $newPWD
}

PROMPT_COMMAND="find_git_branch; $PROMPT_COMMAND"

# PS1 prompt color vars
CYAN="\e[36m"
RED="\e[31m"
GREEN="\e[32m"
DEFAULT="\e[0m"
TIME="[\t]"
DIRNAME="\w"

export PS1="\u@\h:\[$CYAN\]\$(shortpath)\[$GREEN\]\[\$git_branch\]\[$DEFAULT\] \$ "
Run Code Online (Sandbox Code Playgroud)

它运行良好,但有时当我输入或点击先前命令的向上箭头时,部分提示在终端中被覆盖。为什么会发生这种情况?

Kev*_*vin 5

看起来您将您的$git_branch部分包含在非打印字符块 ( \[...\]) 中。