Bash doesn’t calculate prompt length correctly

bashprompt

I've googled around quite a bit on this problem and found a few related problems, like this one: Terminal prompt not wrapping correctly.

My problem is that bash doesn't calculate the length of the prompt correctly, which messes it up when I do things like ctrlr or to scroll through history. This is basically how it should look (without colors).

✔ name@machine ~

01:09 $

When I for example scroll through previous commands with up-arrow, some character gets stuck in the prompt:

✔ name@machine ~

01:09 $m

Sometimes I also get other weird behaviour, like some of the prompt being overwritten (it all goes away when I reload it). My prompt looks like this:

GIT_PROMPT_START_USER="\n_LAST_COMMAND_INDICATOR_ \[$Magenta\]\u\[$Orange\]@\[$White\]\h \[$Yellow\]\[$PathShort\]\[$ResetColor\]"

GIT_PROMPT_END_USER="\n\[$Blue\]$Time12a\[$ResetColor\] $ "

I use something called git-bash-prompt: >https://github.com/magicmonty/bash-git-prompt>.

I think what is messing it up is the time variable, which is defined in another file:

Time12a="\$(date +%H:%M)"

I've tried both \[$Time12a\] and $Time12a in GIT_PROMPT_END_USER, but none of them seem to work. My guess is that bash calculates it wrong because $Time12a represents 5 characters (hh:mm).

How does bash calculate the length of this? Is it possible to explicitly set the length for bash? Answers very appreciated!

Best Answer

So I found out what messed it up, and it was not what I expected :)

It was actually the \[$ResetColor\] that bash for some reason used to count the length forward one step (bash thought my prompt was 1 step longer).

The variable was defined by "bash-git-prompt" along with all the other colors (see the link to the git-repo in the question if you want to look into it). Anyways, the fix was easy. I just overrode their definition with my own:

ResetColor=$(tput sgr0)

Fixed!

(Just btw if somebody else is also having this problem, I have already overridden all the other colors I used with my own definitions using $COLOR=$(tput setaf X) where COLOR is the color you want and X is that color's xterm-256 number.)

Related Question