Check if current directory is a Git repository

anon picture anon · Feb 1, 2010 · Viewed 105.1k times · Source

I am writing a series of scripts for Git management in zsh.

How do I check if the current directory is a Git repository? (When I'm not in a Git repo, I don't want to execute a bunch of commands and get a bunch of fatal: Not a git repository responses).

Answer

jabbie picture jabbie · Feb 1, 2010

Copied from the bash completion file, the following is a naive way to do it

# Copyright (C) 2006,2007 Shawn O. Pearce <[email protected]>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.

if [ -d .git ]; then
  echo .git;
else
  git rev-parse --git-dir 2> /dev/null;
fi;

You could either wrap that in a function or use it in a script.

Condensed into a one line condition suitable for bash and zsh

[ -d .git ] && echo .git || git rev-parse --git-dir > /dev/null 2>&1