Is it possible to set MYSQL_PS1 with colors without messing up prompt line width calculation?

Viewed 96

Consider the following setting for MySQL_PS1:

GREEN="$(echo -e '\033[01;32m')"
BLUE="$(echo -e '\033[01;34m')"
RESET="$(echo -e '\033[00m')"
export MYSQL_PS1="${GREEN}STAGING-\\d${BLUE} >${RESET} "

When I start mysql, and type a command that is longer than the visual line length, it wraps without a new line, overwriting the beginning of line.

I tried the \[ \] trick mentioned here from here.

export MYSQL_PS1="\[${GREEN}\]STAGING-\\d\[${BLUE}\] >\[${RESET}\] "

Unfortunately, it produced this prompt instead of correctly excluding the escape characters from the line length.

] >\[\]  >[\] ]   >\[\] ]STAGING-\d\[\] >\[\] STAGING-messenger[\] >\[\]

Is there a way to set colors in MYSQL_PS1 without messing up the estimated line length?

1 Answers

I found the answer in this comment, which I will repost here.

The correct incantation is to surround the escape sequence with \001 and \002.

GREEN="$(echo -e '\001\033[01;32m\002')"
BLUE="$(echo -e '\001\033[01;34m\002')"
RESET="$(echo -e '\001\033[00m\002')"
export MYSQL_PS1="${GREEN}STAGING-\\d${BLUE} >${RESET} "
Related