Dynamic elements in bash PS1

I have put the following in my ~/.localsh file to customize my bash prompt when working with git.

Basically I want to get the current branch displayed in my terminal.
The gitk tool shows branches with green background and black foreground, so thats what I’m trying to do.

  • Git - Use port 9418 for remote on github
  • How to make quick backup of untracked files which I want to delete by git clean?
  • Revert svn files by file pattern
  • Running .sh scripts in Git bash
  • bash file returns unexpected token `$'do\r''
  • Installing bundler within Jenkins docker image
  • What I have works, but when I press the up arrow on the keyboard to scroll back through previous commands it gets overwritten.

    This stuff has happened to be before when you I din’t end a color sequence with [\e[0m].
    Now it is happening to me because of calling getgitbranch function. I think it has something to do with the terminal not knowing how long the prompt is.

    So, heres the question…
    How do I correctly use dynamic elements in my bash prompt and not get it hosed up when I use the up arrows?

    function getgitbranch()
    git branch | grep "^\*" | cut -c3-
    function blabla()
    PS1="$PS1\[\e[0;30m\]\[\e[42m\]\[\$(getgitbranch)\]\[\e[0;49m\]\[\e[0m\] "
    PS1="$PS1 \[\e[1;31m\]>\[\e[0m\] "
    export PS1

  • How to remove selected commit log entries from a Git repository while keeping their changes?
  • git commit --verbose equivalent in mercurial?
  • Cannot get git extensions to push something to github SSH problems
  • How to conclude your merge of a file?
  • ways to publish pages in github using markdown without having to install jekyll or other tools
  • RStudio: git add --all from the UI
  • One Solution collect form web for “Dynamic elements in bash PS1”

    Remove the \[\] from around the $(getgitbranch). The characters output by that function actually occupy space on the screen so you want Bash to account for them. Using \[\] says don’t count the characters that appear within.

    Git Baby is a git and github fan, let's start git clone.