Terminal prompt not wrapping correctly

Non-printable sequences should be enclosed in \[ and \]. Looking at your PS1 it has a unenclosed sequence after \W. But, the second entry is redundant as well as it repeats the previous statement "1;34".

\[\033[01;32m\]\u:\[\033[01;34m\] \W\033[01;34m \$\[\033[00m\]
                  |_____________|               |_|
                         |                       |
                         +--- Let this apply to this as well.

As such this should have intended coloring:

\[\033[1;32m\]\u:\[\033[1;34m\] \W \$\[\033[0m\]
                               |_____|
                                  |
                                  +---- Bold blue.

Keeping the "original" this should also work:

\[\033[1;32m\]\u:\[\033[1;34m\] \W\[\033[1;34m\] \$\[\033[0m\]
                                  |_|         |_|
                                   |           |
                                   +-----------+-- Enclose in \[ \]

Edit:

The reason for the behavior is because bash believes the prompt is longer then it actually is. As a simple example, if one use:

PS1="\033[0;34m$"
       1 2345678

The prompt is believed to be 8 characters and not 1. As such if terminal window is 20 columns, after typing 12 characters, it is believed to be 20 and wraps around. This is also evident if one then try to do backspace or Ctrl+u. It stops at column 9.

However it also does not start new line unless one are on last column, as a result the first line is overwritten.

If one keep typing the line should wrap to next line after 32 characters.


It is mostly to do with the size of the window assumed by the terminal is not the same as your actual window size. If you are using bash, you can try this.

$ shopt checkwinsize

If you don't get

checkwinsize    on

Then activate it with

$ shopt -s checkwinsize

Then just attempt running another command (like ls) or resizing the window once, the above works for me every time.

For Redhat systems particularly, the issue is often caused by misconfiguring ~/.bashrc not to call /etc/bashrc. Normally, bash loads ~/.bashrc which is expected to call /etc/bashrc, which by default contains shopt -s checkwinsize.


I once read somewhere (don't know where anymore) that using \001 and \002 instead of \[ and \] can solve this issue. It did for me.

By the way, defining PS1 does not have to look ugly.

green="\001$(tput setaf 2)\002"
blue="\001$(tput setaf 4)\002"
dim="\001$(tput dim)\002"
reset="\001$(tput sgr0)\002"

PS1="$dim[\t] " # [hh:mm:ss]
PS1+="$green\u@\h" # user@host
PS1+="$blue\w\$$reset " # workingdir$

export PS1
unset green blue dim reset