Detect git Directory with Bash

By  on  

One interesting aspect of working at Mozilla is that Firefox lives in a mercurial repository while several other projects live on GitHub in a git repository. While most focus on either Firefox or another project, I switch between both, leaving me running git commands inside the mercurial repository and hg commands inside git repos. It's a frustration that I've lived with for a while so I sought to find a unified way of completing common tasks.

The first step was learning to detect git from command line:

if git rev-parse --git-dir > /dev/null 2>&1; then
  # git repo!
else
  # NOT a git repo!
fi

The if statement above detects a git repository, the else means the current directory is not inside a git repo.

One frequent task is checking out master and pulling the latest code from upstream, so I create an alias to do just that:

master() {
  if git rev-parse --git-dir > /dev/null 2>&1; then
    git checkout master && git pull upstream master
  else
    hg pull && hg checkout "last(public())"
  fi
}

This alias will save me time and frustration moving forward, and I'm sure I'll find other aliases to create based on git detection!

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

Discussion

  1. bryanYangGaoFei

    shell is powerful tool !

  2. Very true! Multiple projects on different repositories can be frustrating, especially if you keep messing up on the commands. Can you tell in more detail how to create an alias in Git bash? I haven’t used it a lot so I am not very familiar with it.

  3. Thanks a lot, I test this to fool it by creating empty folder/.git/config file and it complaint that not a git repository.

    I usually use

    -f .git/config

    .

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!