.bashrc edit messes up terminal command arrow-up history print

I wanted to give my terminal prompt in Ubuntu a more personal look, and wanted to change the text prior to the '$' when writing a command.

From what I've found this is done by editing the .bashrc file in the home directory, so I went in there and changed

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

to

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='\e[1;32m[\W]\$ \e[m'
fi

This works and the terminal looks the way I want it to.

But after some time when entering a couple of commands when I use the arrow-up key to get to the command history, things get weird.

From a clean line and pressing the arrow-up key is works. When pressing it again the text that was on the line gets capped at about ~15 characters and the new command in the history (that is supposed to be displayed) gets capped by a few characters in the beginning, and they are sort of merged together on the command line.

E.g. my two most recent commands are

Java Test4 words-250.txt words-250-in.txt
Javac Test4.java

When pressing the arrow-up key once, the first line is displayed, as it should. When pressing it a second time, this is displayed:

Java Test4 worc Test4.java

Despite this weird output, the terminal works fine. If for instance I press enter after doing the above, Javac Test4.java will run. If I instead try to delete the entire line using backspace, I am only able to delete up until the line says

Java Test4

and if pressing enter after that I get a new empty line, just as if the line was empty when pressing enter.

All of this goes away if I reset the .bashrc file.

Why does this happen and how can I fix it?


Solution 1:

I have no idea why (never really understood the escape codes), but adapting the other prompt seems to work:

PS1='\[\033[1;32m\][\W]\$ \[\033[00m\]'

Apparently, you need to enclose the escape sequences in \[...\], to tell bash not to count them while determining the prompt width. Therefore, both the above PS1 and the following would work equally well:

PS1='\[\e[1;32m\][\W]\$ \[\e[m\]'