Recently, I have been playing around a lot with color in the terminal and, therefore, with escape sequences, too. I've read the relevant parts of the Bash manpage along with numerous helpful pages on the Net.
I've got most of what I want working; a nice color Bash prompt, for example. That said, I am still somewhat confused over when I should use (or need to use) the "non-printing escape sequence" characters. Those would be \[
and \]
.
If I don't use them in PS1 when defining my prompt then my prompt most definitely does not display properly. If I do use them, everything is fine. Good.
But, outside of PS1, they don't seem to operate the same way. For example, to make scripts more readable I have defined a variable $RGB_PURPLE
which is set via a simple function c8_rgb()
. The end result is that the variable contains the value \[\e[01;38;05;129m\]
which turns on a bold purple foreground color.
When I use this variable in PS1, it does what I expect. If I use it via printf
or echo -e
it "half" works. The command printf "${RGB_PURPLE}TEST${COLOR_CLR}\n"
(where COLOR_CLR
is the escape sequence to reset text properties) results in the following display: \[\]TEST\[\]
where everything except the first \[
and final \]
are displayed in purple.
Why the difference? Why are these brackets printed instead of being processed by the terminal? I would have expected them to be treated the same when printed as part of the prompt as when printed by other means. I don't understand the change.
It seems, empirically, that these characters must be used inside the prompt definition, while they shouldn't be used in pretty much every other case. This makes it difficult to use a common function, like my c8_rgb()
function mentioned above, to handle escape sequence generation and output since the function cannot know whether its result will be in a prompt config or someplace else.
And a quick related question: are echo -e
and printf
essentially the same with regards to outputting escape sequences? I typically use printf, but is there any reason to favor one over the other?
Can anyone explain this apparent subtle difference? Are there any other oddities I should be aware of when using escape sequences (usually just for color) in the terminal? Thanks!