bash – Fix .bashrc PS1 Configuration Rendering Issues

bashprompt

I essentially know what the problems is, in that I need to use \[...\] as a way to escape (non-space?) characters, and allow bash to correctly calculate the width of my prompt.

However, I cannot iron out all the problems and have been using trial and error as I don't quite understand where exactly I need all my \[...\] placed.

STARTCOLOR='\[\e[0;31m\]'
ENDCOLOR='\[\e[0m\]'
BACKGROUND='\[\e[47m\]'
export PS1="$STARTCOLOR$BACKGROUND\u@\h \[\t\]$ENDCOLOR\w>\$?\$\]"

Is what I am using. The only issue now seems if I use the arrow keys to scroll previous commands for too long the \w>\$?\$\ part of my PS1 will disappear. It happens too if I reverse back with arrow keys after moving forward with previous commands.

Best Answer

The problem is that you are using the non-printing markers for something that gets printed out (\t - the timestamp)

STARTCOLOR='\[\e[0;31m\]'
ENDCOLOR='\[\e[0m\]'
BACKGROUND='\[\e[47m\]'
export PS1="$STARTCOLOR$BACKGROUND\u@\h \t$ENDCOLOR\w>\$?\$ "

The \[ ... \] is only for surrounding non-printing character sequences, such as colour codes.

Related Question