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?

6
  • 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, 2019 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.
    – Trachyte
    Jul 10, 2019 at 5:38
  • It doesn't work fine. As I said, the prompt breaks easily.
    – muru
    Jul 10, 2019 at 5: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? Jul 10, 2019 at 5: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, 2019 at 5:56

1 Answer 1

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.

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