While setting up my development environment [Windows 7] for our newest project, I noticed my Cygwin Terminal was not displaying git branches on my bash prompt:
# Actual Riley /cygdrive/c/users/Riley/Documents/Project-Directory $ # Expected Riley /cygdrive/c/users/Riley/Documents/Project-Directory (repository-name) $ |
Since we are working with GitHub and making pull requests, this stuck out as an important feature.
Solution:
Before modifying your existing .bashrc file, it’s a good idea to make a backup copy of it:
# Change Directory to ~ cd ~ # Ensure the .bashrc file exists in this directory ls -a # Make a backup copy of the file cp .bashrc .bashrc-backup # Open the .bashrc file for editing in notepad [or a editor of your choice :)] notepad .bashrc |
Add the following code at the bottom of the .bashrc file with your editor and save it:
export PS1='\[\033[01;32m\]\h\[\033[01;34m\] \w\[\033[31m\]$(__git_ps1 "(%s)") \[\033[01;34m\]$\[\033[00m\] ' |
Now apply the change via bash:
# Apply the settings
source .bashrc |
Your color scheme should have a noticeable change, along with your git branches displaying inline!
Update! For OS X Users:
For users with terminals such as iTerm2 and a .bash_profile, the following snippet will work:
# Git branch and color variables in bash prompt parse_git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' } export PS1="\[\033[01;32m\]\h\[\033[01;34m\] \w\[\033[31m\]\$(parse_git_branch)\[\033[00m\] $ " |
Update! For MacOS Catalina (zsh) Users:
For users on MacOS Catalina, which uses zsh, the following snippet will work (credit to https://gist.github.com/reinvanoyen/05bcfe95ca9cb5041a4eafd29309ff29).
function parse_git_branch() { git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p' } COLOR_DEF=$'\e[0m' COLOR_USR=$'\e[38;5;243m' COLOR_DIR=$'\e[38;5;197m' COLOR_GIT=$'\e[38;5;39m' setopt PROMPT_SUBST export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ ' |