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 post-commit hook - script on committed files
  • How do I enable auto-complete for a git-flow alias?
  • sh.exe": emacs: command not found (Git bash Windows)
  • Git in PyCharm using a pre-existing repository
  • Get Git repo url using absolute path
  • How to determine last merged branch in git?
  • 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="$PS1\[\e[0;30m\]\[\e[42m\]\[\$(getgitbranch)\]\[\e[0;49m\]\[\e[0m\] "
    PS1="$PS1\[\e[1;35m\][\[\e[0m\]"
    PS1="$PS1\[\e[1;33m\]\w\[\e[0m\]"
    PS1="$PS1\[\e[1;35m\]]\[\e[0m\]"
    PS1="$PS1 \[\e[1;31m\]>\[\e[0m\] "
    export PS1
    }
    

  • oh-my-zsh slow, but only for certain Git repo
  • Exclude file in Visual Studio from git Commit by default
  • Svn server is dead… can I still convert to Git?
  • Why does a seemingly possible merge using Git have conflicts?
  • working with hosted git repositories and sublime text
  • Is it bad to commit all files always on git?
  • 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.