Display Git Branch or Tag Names in your Bash Prompt

27th April 2013

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.

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.

About the Author

Picture of Oliver

Oliver Davies is a Web Developer, System Administrator and Drupal specialist based in the UK. He is a Senior Developer at Microserve and also provides freelance consultancy services for Drupal, Symfony and Laravel applications and Linux servers.

Availability

  • Currently no spare part-time capacity.
  • Currently no spare full-time capacity.