I was messing around with the color codes trying to understand how color code is used in bash script and I found that it works fine without including \[\] around it as in here:


export PS1="$red\u$green\$(__git_ps1)$blue \W"

..gives the same result as that:

export PS1="$red\u$green\$(__git_ps1)$blue \W"

So is the second form necessary?

  • @muru I took a look.. none of that helps with my question. – mdtair Jul 10 '19 at 5:26
  • It doesn't? OP asks "Is this just something I learn to live with? Is there some piece of magic which I should know?" and answer says "Non-printable sequences should be enclosed in [ and ] ... The reason for the behavior is because bash believes the prompt is longer then it actually is." – muru Jul 10 '19 at 5:28
  • As for "I found that it works fine without including []", I'd say you haven't really used your prompt much. Even just browsing history with arrow keys will break it. i.stack.imgur.com/VFOWn.png – muru Jul 10 '19 at 5:30
  • It still works fine without it.. why? That's my question which still hasn't been answered.. which is why it's not a duplicate. – mdtair Jul 10 '19 at 5:38
  • It doesn't work fine. As I said, the prompt breaks easily. – muru Jul 10 '19 at 5:39

If your prompt contains non-printing characters that are not enclosed in \[...\], then the shell will miscalculate the width of the prompt.  As a result, it will be confused about where the cursor is, and it will update the display erroneously.  A classic example of this occurs if you type a command so long that it's longer than the window is wide, so it wraps to the next line, and then you backspace back up to the first line.

| improve this answer | |

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