Skip to content

Instantly share code, notes, and snippets.

@e-cite
Last active May 6, 2023 17:57
Show Gist options
  • Save e-cite/6a01e1f426ddeb2553258fc24a1dc18e to your computer and use it in GitHub Desktop.
Save e-cite/6a01e1f426ddeb2553258fc24a1dc18e to your computer and use it in GitHub Desktop.
Show git branch in bash prompt

Show current git branch in bash prompt

According to: https://thucnc.medium.com/how-to-show-current-git-branch-with-colors-in-bash-prompt-380d05a24745

Make these settings in ~/.bashrc:

  1. Add function to get current git branch:
    parse_git_branch() {
         git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
    }
  2. Search variable PS1 and add this part before the prompt $:
    \[\e[91m\]\$(parse_git_branch)\[\e[00m\]
    This sets color-code red and returns the output of the parse_git_branch function. Beware of quotes!

Result:

# ~/.bashrc
parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
...
if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\e[91m\]\$(parse_git_branch)\[\e[00m\]\$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w\[\e[91m\]\$(parse_git_branch)\[\e[00m\]\$ "
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment