Why does this bash prompt sometimes keep part of previous commands when scrolling history?

The color codes need to be wrapped in square brackets. The brackets inform bash that the enclosed text should not be printed

building on @Phreditor's example, this shows that any formatting done after the newline will result in the original issue:

export PS1="\n\n\[\033[01;33m[\w]\033[00m\n\033[0;90m\$ "

wrapping the format code in [] ensures that annoying behavior never happens:

export PS1="\n\[\[\033[01;33m\][\w]\[\033[00m\]\n\[\033[0;90m\]\$ "

The documentation: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/nonprintingchars.html

Since PS1 formatting causes the value to be so long and hard to read I put the format codes in variables:

BYELLOW='\[\033[01;33m\]'
IBLACK='\[\033[0;90m\]'
PS_CLEAR='\[\033[0m\]'
export PS1="\n${BYELLOW}[\w]${PS_CLEAR}\n${IBLACK}\$ "

I had the same problem and it was related to the color definitions.

In my case, I have a multi-line prompt (gives most space for current command regardless of path length displayed by prompt).

Bad version:

export PS1="\n\n\[\033[01;33m[\w]\n\033[00m\$ "

Good version:

export PS1="\n\n\[\033[01;33m[\w]\033[00m\n\$ "

\033[00m terminates the color. If it is after the new line (\n), it prevents proper redraw in the terminal, to overwrite previous commands with background color. Moving it behind the new line resolved the problem.

(using Terminal in Mac OS 10.8)


Somewhere your prompt is fubar. What usually happens is that your shell thinks its outputting non-printable term codes and expecting it to take up space. The best advice I can give you is to systematically add to (or take away from) your prompt until this behavior stops to isolate the code that is causing this issue.

Tags:

Bash

Prompt