Bash – Colored text set up with PS1 and colored output from commands mess each other up

bashcolorsprompt

I have PS1 that ends with an opening color sequence (like \[\e[0;32m\]) to have all text in the terminal colored (green in this case). However, when I use a command such as ls (which is aliased to ls --color=auto in my .bashrc) the colors in the output are a little messed up: green up to the first "colored" word, and the following uncolored text is white instead of green.

Is there a way to have clean output in all cases? I'm okay with white as "default" text color when the output has colors, but I'd like it to be consistent.

Of course, I'd most like a solution that would automatically apply to all commands and that wouldn't require me to change the way I invoke them.

Personally, I don't have any ideas. Maybe something can be done to search for escape sequences in the output "on the fly" and perform some substitutions? I don't know how to implement this, though, especially so that it's done "behind the scenes".

Best Answer

The reason is because you're doing it wrong.

You said that you have an "open" color sequence at the end of your prompt. This is wrong. Colors do not nest. There's no "open" and "close". It's "switch to ..." or "reset to default" (which is actually "switch to 0"). So when ls --color=auto switches color for something when it's done it will issue the sequence to reset to the default. It's not "go back to what it was before".

Set the terminal to use the color of text that you want to be "default" (i.e., palette number 0). Then if you want your prompt a different color set it at the beginning and a reset at the end.

For more information read the Bash Prompt HOWTO Chapter 6. ANSI Escape Sequences: Colours and Cursor Movement documentation.

Related Question