This question already has an answer here:

I added a function to my .bashrc to parse the git branch I'm currently working in and display it in my bash-prompt according to several tutorials on this topic. My code snippet looks like this:

parse_git_branch() { 
   BRANCH=$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
   if [ "$BRANCH" != "" ]; then
      echo -e "[\e[1;31m⎇ $BRANCH\e[1;37m]"
      echo "╼"
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[1;37m\]┌[\[\033[1;32m\]\u\[\033[1;37m\]@\[\033[1;32m\]\H\[\033[1;37m\]] [\w]\n└$(parse_git_branch) \[\033[00m\]'

    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
unset color_prompt force_color_prompt

This does as expected print the current git branch in red if there is one: screenshot

However, if the command is really long, the line doesn't break anymore: another screenshot

The problem goes away if I don't use the -e flag for echo in parse_git_branch, but I need it to color the branch red.

Any ideas on how to fix this?

All the other solutions I found while googling this just print either the colored git branch or nothing, so they don't quite work for me since i want it to print the git branch if there is one and if not print that -character in white.

marked as duplicate by wjandrea, karel, Fabby, Eric Carvalho, muru May 13 '18 at 4:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Wrap the color sequences in readline escapes like so:

echo -e "[\001\e[1;31m\002⎇ $BRANCH\001\e[1;37m\002]"

The readline escapes are \001 at the start of a non-printing sequence, and \002 at the end. These are equivalent to \[ and \], respectively, in the PS1 string.

Source: archemiro's answer on bash prompt and echoing colors inside a function - Stack Overflow

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