5

I have the following bash prompt:

YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
RESET='\e[0m'

export PS1="$GREEN[\W]$YELLOW \$(__git_ps1 \"(%s) \")$RESET\\$ "

It looks like this:

enter image description here

Which is what I want. However, when I enter a long line, it does not break the line at all but rather overwrites the current one from the beginning of the line. When this happens and I hit backspace, everything in that line will disappear. How can I fix this?

2 Answers 2

4

You forgot to wrap the value of $RESET.

RESET='\[\e[0m\]'

Bash must know how long the prompt is in order for word-wrap to work correctly, and everything not between \[ and \] is counted.

4
  • It's not about prompt length but the escape sequence parameters list. You could add several of them e.g. to make the text bold, inverted and underlined etc.
    – Rajish
    Sep 20, 2011 at 14:10
  • @Rajish: Okay, and why would that break line-wrapping? Sep 20, 2011 at 14:11
  • @grawity The \[ and \] escapes delimit non-printing characters sequence. Leaving them out probably breaks some terminal behaviour or internal bash parsing rules. gnu.org/s/bash/manual/bash.html#Printing-a-Prompt
    – Rajish
    Sep 20, 2011 at 14:50
  • 1
    @Rajish: Which is exactly what my answer says. Leaving them out breaks the internal bash prompt-length-computation "rules". Sep 20, 2011 at 14:54
3

More portable using tput:

fgred="$(tput setaf 1)"
fggreen="$(tput setaf 2)"
fgyellow="$(tput setaf 3)"
fgblue="$(tput setaf 4)"
fgpurple="$(tput setaf 5)"
fgcyan="$(tput setaf 6)"
fgwhite="$(tput setaf 7)"

bgred="$(tput setab 1)"
bggreen="$(tput setab 2)"
bgyellow="$(tput setab 3)"
bgblue="$(tput setab 4)"
bgpurple="$(tput setab 5)"
bgcyan="$(tput setab 6)"
bgwhite="$(tput setab 7)"

bold="$(tput bold)"
underline="$(tput smul)"
reset="$(tput sgr0)"

export PS1="${fggreen}[\W]${fgyellow} \$(__git_ps1 \"(%s) \")${reset}\\$ "
3
  • Wow. I've never heard of tput before. Thanks! Sep 20, 2011 at 14:49
  • tput is good, but eh, I've never seen a not VT220-compatible terminal [emulator] in active use these days. Also, noting lack of \[ \]. Sep 20, 2011 at 14:55
  • 1
    @grawity: the other advantage of tput is that you know what to search in the manual if you don't understand what the script does.
    – Benoit
    Sep 20, 2011 at 14:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .