Problem with 256-bit Color Codes in Bash Prompt – Fix Guide

bashcolorsprompt

Here is my bash prompt; I'm using ANSI escape sequences

reset="\033[0m";
blue="\033[38;5;20m";
cyan="\033[38;5;38m";
green="\033[38;5;35m";
yellow="\033[38;5;227m";
white="\033[38;5;250m";

# Set the terminal title to the current working directory.
PS1="\[\033]0;\w\007\]";
PS1+="\[${yellow}\]\u"; # username
PS1+="\[${white}\]@";
PS1+="\[${green}\]\h"; # host
PS1+="\[${white}\]:";
PS1+="\[${cyan}\]\W"; # working directory
PS1+="\$(prompt_git \"${blue}\")"; # Git repository details
PS1+="\[${white}\]\$ \[${reset}\]"; # `$` (and reset color)
export PS1;

It looks fantastic, but sometimes the terminal seems to have issues calculating the length of the prompt. This happens both locally on OSX, and when SSHing into an Ubuntu server (on OSX and on Windows through PuTTY)

For example, this happens. I first typed "git add [filename]" with tab completion, then I hit the "Home" key to go back to the front of the line and replace "git add" with "vi". As you can see it's pretty messed up.

enter image description here

Also, if I then hit "End" to get to the end of the line it takes me way past the ".php" with several blank spaces.

enter image description here

This happens both when editing a new line and when editing a line in my history (using up arrow. It displays correctly but as soon as I use arrow keys or Home/End it messes up)

Press Ctrl+L to clear doesn't fix it, I basically have to start over and retype the whole line to avoid issues.

Best Answer

This line

PS1+="\$(prompt_git \"${blue}\")"; # Git repository details

does not have the \[ and \] markers used by bash to tell it to not count columns for each character enclosed. If not told otherwise, it assumes that printable characters should be counted.

For discussion:

Related Question