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

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.