Skip to content

Instantly share code, notes, and snippets.

@githubteacher
Created February 29, 2016 20:59
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save githubteacher/e75edf29d76571f8cc6c to your computer and use it in GitHub Desktop.
Save githubteacher/e75edf29d76571f8cc6c to your computer and use it in GitHub Desktop.
Adding your Git branch to your command prompt

To show your active Git branch in your command prompt, you will need to do the following:

  • If you are on a Mac, you can add the code shown below to your .bash_profile file.
  • If you are on Linux, you will add the code shown below to your .bashrc file.
  • If you are on Windows, you probably aren't reading this because Windows provides this behavior by default.

The Script

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\w\[\033[36m\]\$(parse_git_branch) \[\033[00m\] > "

Or, another option:

function parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
 
RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
 
PS1="$GREEN\u@\h$NO_COLOR:\w$YELLOW\$(parse_git_branch)$NO_COLOR\$ "
@KalikaKay
Copy link

For Linux users - you will need to paste code at the end of the .bashrhc file. Otherwise, variable may be overwritten by normal processing.

@drashna
Copy link

drashna commented Oct 19, 2018

If you are on Windows, you probably aren't reading this because Windows provides this behavior by default.

You're making assumptions that may not be correct.

Git for Windows does this, yes. But MSYS2 does not, and bash for windows doesn't either (IIRC).

@mslinn
Copy link

mslinn commented Dec 17, 2019

I like this incantation better:

parse_git_branch () {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo "${ref#refs/heads/}"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment