2

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:

This..

red="\033[38;5;203m"
export PS1="$red\u$green\$(__git_ps1)$blue \W"

..gives the same result as that:

red="\[\033[38;5;203m\]"
export PS1="$red\u$green\$(__git_ps1)$blue \W"

So is the second form necessary?

Trachyte
  • 141
  • 5
  • 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. https://i.stack.imgur.com/VFOWn.png – muru Jul 10 '19 at 05: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. – Trachyte Jul 10 '19 at 05:38
  • It doesn't work fine. As I said, the prompt breaks easily. – muru Jul 10 '19 at 05:39
  • As muru says, if you haven't *seen* it break, you just haven't used it heavily enough. Have you tried typing a command so long that it's longer than the window is wide, so it wraps to the next line, and then backspacing back up to the first line? – Scott - Слава Україні Jul 10 '19 at 05:42
  • @Scott This is the clear enough answer I was looking for.. I'd say this comment should be resubmitted as an answer.. again.. the answers to the other question mentioned weren't clear enough.. neither were the previous comments here. – Trachyte Jul 10 '19 at 05:56
  • I'm sorry, but that really looks like a dupe of the question you asked which was "do I need to include the \[" and the answer is yes. You seem to also have been wondering what breaks if you don't include them, but that isn't what your question actually asked for, so the dupe seems valid. – terdon Jul 10 '19 at 10:03

1 Answers1

3

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.