Why does my bash prompt sometimes get overwritten?

泪湿孤枕 提交于 2019-12-08 13:07:23

问题


Here's the relevant parts of my 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\] \$ "

It works well, but sometimes as I type or hit the up arrow for previous commands, part of the prompt gets overwritten in the terminal. Why does this happen?


回答1:


Looks like you're including your $git_branch part in a non-printing-chars block (\[...\]).



来源:https://stackoverflow.com/questions/23392517/why-does-my-bash-prompt-sometimes-get-overwritten

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!