How to show git branch in terminal and change terminal colours

How to show git branch in terminal and change terminal colours

To show git branch in terminal you need to edit your .bash_profile file or create if you don't have it. This file should be in your user's root directory. Open it with any text editor. For example:

open -t ~/.bash_profile

Then add this code to the bottom of .bash_profile:

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u ::\[\033[01;33m\] \W\[\033[00m\] -\[\033[00;32m\]\$(parse_git_branch)\[\033[00m\] $ "

Where:

  • \u - stands for your user name;
  • \W - shows your current folder;
  • \$(parse_git_branch) - displays your current git branch;
  • Parts of code like \[\033[00;32m\] are responsible for changing the colours in terminal.

Eventually now your terminal input will look like this:

username :: folder - (git branch) $

Here are some other terminal colour codes you can use:

Regular colours:

  • [\033[00;30m] - Black
  • [\033[00;31m] - Red
  • [\033[00;32m] - Green
  • [\033[00;33m] - Yellow
  • [\033[00;34m] - Blue
  • [\033[00;35m] - Purple
  • [\033[00;36m] - Cyan
  • [\033[00;37m] - White

High intensity:

  • [\033[00;90m] - Black
  • [\033[00;91m] - Red
  • [\033[00;92m] - Green
  • [\033[00;93m] - Yellow
  • [\033[00;94m] - Blue
  • [\033[00;95m] - Purple
  • [\033[00;96m] - Cyan
  • [\033[00;97m] - White

Background:

  • [\033[40m] - Black
  • [\033[41m] - Red
  • [\033[42m] - Green
  • [\033[43m] - Yellow
  • [\033[44m] - Blue
  • [\033[45m] - Purple
  • [\033[46m] - Cyan
  • [\033[47m] - White

Backgrounds with high intensity:

  • [\033[00;100m] - Black
  • [\033[00;101m] - Red
  • [\033[00;102m] - Green
  • [\033[00;103m] - Yellow
  • [\033[00;104m] - Blue
  • [\033[10;95m] - Purple
  • [\033[00;106m] - Cyan
  • [\033[00;107m] - White

You can replace any leading second 0; with 1; for bold colours and replace any leading second 0; with 4; to get text underlined.

Note that if you already have PS1 variable, then you'll just need to modify it by adding this code to the end of PS1:

-\[\033[00;32m\]\$(parse_git_branch)\[\033[00m\] $