Adding ANSI color escape sequences to a bash prompt results in bad cursor position when recalling/editing commands

StackOverflow https://stackoverflow.com/questions/17432993

Question

If I set my command prompt like:

export PS1='\033[0;33m[\u@\h \w]\$ \033[00m'

The color of the prompt will be yellow and everything after the '$' character will be the default terminal color. This is what I expect. However, If I recall a command line and attempt to edit it, moving the cursor -- either UpArrow/Ctrl-A (set -o emacs) or ESC K (set -o vi) if the command line I'm trying to edit is long enough, the cursor is not positioned at the beginning of the command. Typing either Ctrl-A (set -o emacs) or ^ (set -o vi) will not move the cursor to what I'm seeing as the beginning of the recalled line on the screen. Similarly, attempting to position the cursor to the end of the line (Ctrl-E or $, depending) results in it being placed several characters past what appears to be the end of the line. It looks like bash is getting confused by the escape characters I've added to the prompt. Is this just something I'll have to deal with, changing my prompt to a monochromatic one when I wish to edit recalled lines, or is there a way to get bash to correctly allow the editing of recalled commands with a colorful prompt?

Was it helpful?

Solution

You need to enclose the non-printing characters in \[ ... \] so that bash knows to ignore them when computing the length of the prompt:

export PS1='\[\033[0;33m\][\u@\h \w]\$ \[\033[00m\]'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top