Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Created July 6, 2017 23:54
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettinternet/0d2225ffb6b224c515643f630a65b463 to your computer and use it in GitHub Desktop.
Save brettinternet/0d2225ffb6b224c515643f630a65b463 to your computer and use it in GitHub Desktop.
Check if directory is a git repo or not
# from https://stackoverflow.com/questions/2180270/check-if-current-directory-is-a-git-repository
[ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1
# Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
# 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;
@avatar-lavventura
Copy link

avatar-lavventura commented Nov 24, 2020

Why are you calling git rev-parse --git-dir 2> /dev/null; ?

@westofer
Copy link

westofer commented Nov 28, 2020

https://stackoverflow.com/questions/2180270/check-if-current-directory-is-a-git-repository
edit: wrong link

@avatar-lavventura

Why are you calling git rev-parse --git-dir 2> /dev/null; ?

@MichaelCurrin
Copy link

Regarding questions above,

This checks for .git in current directory only.

[ -d .git ]

If you are in a subfolder it won't work. But rev-parse will work.

cd my-repo
cd docs
git rev-parse --git-dir
# Success! Output:
# /Users/mcurrin/repos/my-repo/.git

# Test the failure case.
cd ~
git rev-parse --git-dir
# Output
fatal: not a git repository (or any of the parent directories): .git

The 2> /dev/null bit hides the stderr on an error.

@MichaelCurrin
Copy link

I don't think you even need the --git-dir flag since git rev-parse alone will return success but not text if in a git repo, or error and error message if not.

@avatar-lavventura
Copy link

avatar-lavventura commented Mar 3, 2021

@MichaelCurrin Thanks for the explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment