Display Git Branch or Tag Names in your Bash Prompt

27th April 2013

Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

Whilst watching Drupalize.me's recent Introduction to Git series, I thought it was useful the way that the current Git branch or tag name was displayed in the bash prompt.

Here's how to do it.

For example (with some slight modifications):

oliver@oliver-mbp:~/Development/drupal(master) $
oliver@oliver-mbp:~/Development/a11y_checklist(7.x-1.0) $

Here's how to do it.

To begin with, create a new file to contain the functions,

vim ~/.bash/git-prompt

Paste the following code into the file, and save it.

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

parse_git_tag () {
  git describe --tags 2> /dev/null
}

parse_git_branch_or_tag() {
  local OUT="$(parse_git_branch)"
  if [ "$OUT" == " ((no branch))" ]; then
    OUT="($(parse_git_tag))";
  fi
  echo $OUT
}

Edit your .bashrc or .bash_profile file to override the PS1 value.

vim ~/.bashrc

Add the following code at the bottom of the file, and save it.

source ~/.bash/git-prompt
PS1="\u@\h:\w\$(parse_git_branch_or_tag) $ "

Restart your Terminal or type source ~/.bashrc to see your changes.

Questions? Comments? I’m @opdavies on Twitter, or send me an email.

Tags

About the Author

Picture of Oliver

Oliver Davies is a full-stack Web Developer and System Administrator based in the UK. He is a Senior Developer at Microserve and a part-time freelancer specialising in Drupal, Symfony and Laravel development and Linux systems administration.