In a Bash Prompt (PS1 variable), I'm calling a function to potentially add text to the prompt: export PS1="\u@\h \$(my_function) \$ "

However, the function in the prompt contains ANSI color codes that change based on the output of the function (sometimes red, sometimes green). Adding "\[" to the PS1 variable should escape those codes as non-printing, but if I do an echo in the function, the "\[" get printed literally in the prompt.

How can I escape these ANSI color codes from within a function for use in a bash prompt?

link|improve this question
feedback

2 Answers

up vote 4 down vote accepted

The readline library accepts \001 and \002 (ASCII SOH and STX) as non-printable text delimiters. These also work in any application that uses readline.

From lib/readline/display.c:243 in bash source code:

243 /* Current implementation:
244         \001 (^A) start non-visible characters
245         \002 (^B) end non-visible characters
246    all characters except \001 and \002 (following a \001) are copied to
247    the returned string; all characters except those between \001 and
248    \002 are assumed to be `visible'. */

The bash-specific \[ and \] are in fact translated to \001 and \002 at y.tab.c:7640.

link|improve this answer
That does it! echo -e "\001\e[31m\002RED" works as expected. Thanks! – MidnightLightning Jun 23 '11 at 20:38
feedback

If you want to use them in the prompt, then you do need to do the \[. But if you want to use it in an echo, you have to use \033[.

link|improve this answer
Hmmm... Adding \033[ before the ANSI command ("\e[31m") and \033] after it seems to make the next printed character in the prompt not print. – MidnightLightning Jun 23 '11 at 20:31
You don't want to do \033] after it. \033[31m starts the color, after that you need to set it back with \033[0m – Wuffers Jun 23 '11 at 20:38
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.