I found this question when looking to refine the GNU readline prompt in a bash script. Like readline in C code, \[
and \]
aren't special but \001
and \002
will work when given literally via the special treatment bash affords quoted words of the form $'string'
. I've been here before (and left unsatisfied due to not knowing to combine it with $'…'
), so I figured I'd leave my explanation here now that I have a solution.
Using the data provided here, I was able to conclude this result:
C1=$'\001\033[1;34m\002' # blue - from \e[1;34m
C0=$'\001\033[0;0m\002' # reset - from \e[0;0m
while read -p "${C1}myshell>$C0 " -e command; do
echo "you said: $command"
done
This gives a blue prompt that says myshell>
and has a trailing space, without colors for the actual command. Neither hitting Up nor entering a command that wraps to the next line will be confused by the non-printing characters.
As explained in the accepted answer, \001
(Start of Heading) and \002
(Start of Text) are the RL_PROMPT_START_IGNORE
and RL_PROMPT_END_IGNORE
markers, which tell bash and readline not to count anything between them for the purpose of painting the terminal. (Also found here: \033
is more reliable than \e
and since I'm now using octal codes anyway, I might as well use one more.)
There seems to be quite the dearth of documentation on this; the best I could find was in perl's documentation for Term::ReadLine::Gnu, which says:
PROMPT
may include some escape sequences. Use RL_PROMPT_START_IGNORE
to begin a sequence of non-printing characters, and RL_PROMPT_END_IGNORE
to end the sequence.