Linux: coloring bash prompt will break carriage return

24

10

When I try to colorize the bash prompt like this:

export PS1="\e[0;31m[\u@\h \W]\$ \e[m "

it breaks the carriage return (instead of going to a new line when line is full, it starts in the same line and erases the input text).

If I remove the color sequence it works fine.
I use Ubuntu 11.10 and terminal (guake has the same bug too).

Abonec

Posted 2011-12-12T19:58:22.687

Reputation: 342

Strange. It works w/o any problem on RedHat 5 and Mac OS X – Matteo – 2011-12-12T20:08:26.440

possible duplicate of PS1 problem, cmd is looping

– user1686 – 2011-12-12T20:10:28.560

Answers

43

You must wrap all escape sequences between \[ and \] in order for 'readline' to correctly calculate the prompt's visible length. Without them, 'readline' thinks the prompt is longer than it is, and doesn't know when the text reaches the margin.

PS1="\[\e[;31m\][\u@\h \W]\$ \[\e[m\]"

user1686

Posted 2011-12-12T19:58:22.687

Reputation: 283 655

2@osirisgothra: The documentation is actually talking about a different thing – skip-csi-sequence is meant to suppress input sequences generated by special keys. – user1686 – 2014-08-22T10:34:33.480

1@MaxHowell you have to wrap each \e[xxm sequence, not the whole string. – Enrico – 2016-05-05T21:12:08.530

Thanks. In my case I just replaced \e[39m with \[\e[;39m\] and it works fine – Herrgott – 2018-06-03T08:03:51.650

Note that \e[;39m expands to \e[0;39m which means "reset all formatting, then set color to 39". It's good in prompts, but it is not in any way related to my post about \[ \]. – user1686 – 2018-06-03T08:09:52.143

4Thanks a ton!! i was trying to find some documentation on it in the official docs but couldnt -- the 'stock' color prompt does employ this 'trick' and I had a hard time at first figuring out what exactly it was for, so thanks for clearing that up --- btw i did actually find the documentation source in 'man readline 3' around line 684 and it says that this is actually called 'skip-csi-sequence' for those who want to know where the documentation on this is. I don't think i would have found it without you pointing me to readline(3) even though i knew about it before-failed to make the connection. – osirisgothra – 2013-02-27T15:27:18.707

What does "wrap" mean? Do you mean wrap the whole thing IN a \[, \]? I guess so, but it doesn't seem to be working for me. – Max Howell – 2013-11-02T20:33:00.423

1

the [ and ] tip worked on bash on OS X 10.8.2 too.

I use:

PS1="[\e[0;37m\W\$(git branch 2>/dev/null | grep -e '* ' | sed 's/^..(.*)/{\1}/') \$ \e[m ]"

which shows me my current git branch in use.

stonefruit

Posted 2011-12-12T19:58:22.687

Reputation: 61

Do you know about "__git_ps1" ? – rafak – 2013-05-05T04:43:15.983

nopes. what magical thing will it do? – stonefruit – 2013-05-19T19:06:42.120