0

My terminal prompt is set using the following configuration in my .profile file:

# Prompt
GREEN=$(tput setaf 2)
LIME_YELLOW=$(tput setaf 190)
MAGENTA=$(tput setaf 5)
WHITE=$(tput setaf 7)
NORMAL=$(tput sgr0)
PS1="\[${WHITE}${MAGENTA}\]\u\[${WHITE}@${GREEN}\]\h \[${LIME_YELLOW}\]\W \[${WHITE}${NORMAL}\]$ "

Generally speaking it works fine but sometimes I end up with an off-by-one error. After a running a few commands and then accessing the history using the up key, some characters seem to be getting garbled. For example:

matt@laptop ~ $ git log

becomes

matt@laptop ~ $ gitlog

or:

matt@laptop ~ $ ssh desktop

becomes

matt@laptop ~ $ssh desktop

The incorrectly displayed command executes normally and appears in history normally too.

Matt
  • 561

1 Answers1

2

The \[ and \] markers are used to surround text that, when displayed on the screen, will take up zero width, such as control sequences that set colors. The @ and any other ordinary text should be outside of the markers.

So instead of

PS1="\[${WHITE}${MAGENTA}\]\u\[${WHITE}@${GREEN}\]\h \[${LIME_YELLOW}\]\W \[${WHITE}${NORMAL}\]$ "

use this

PS1="\[${WHITE}${MAGENTA}\]\u\[${WHITE}\]@\[${GREEN}\]\h \[${LIME_YELLOW}\]\W \[${WHITE}${NORMAL}\]$ "

More info at Bash FAQ 053.

Mark Plotnick
  • 25,413
  • 3
  • 64
  • 82