rurouniwallace
rurouniwallace

Reputation: 2087

Check if directory is git repository (without having to cd into it)

What's a shell command I can use to, using the full directory path, determine whether or not a given directory is a git repository? Specifically, I'd like to be able to do this without being in the directory, and without having to cd into it. I'd also like to be able to do it with a command that returns a simple "true" or "false" (much the way that rev-parse --is-inside-work-tree does), but it's not a requirement.

Upvotes: 34

Views: 26503

Answers (6)

torek
torek

Reputation: 487875

Consider git rev-parse --is-inside-work-tree as well here (with the appropriate -C first as well if/as desired) to check whether this is a working tree. This allows you to distinguish between the "working tree" and "bare repository" cases:

$ git -C .git rev-parse && echo $?
0
$ git -C .git rev-parse --is-inside-work-tree && echo $?
false
0

As always, be aware that if you're not in a Git directory at all, you get an error:

$  git -C / rev-parse --is-inside-work-tree
fatal: not a git repository (or any of the parent directories): .git

which you may wish to discard (git ... 2>/dev/null). Since --is-inside-work-tree prints true or false you'll want to capture or test stdout.

Upvotes: 1

BrandonMFong
BrandonMFong

Reputation: 101

In unix/linux systems, you can run git status and check the exit code echo $?. Anything other than 0 would tell you aren't in a git repo

Upvotes: 0

ypnos
ypnos

Reputation: 52327

Use git -C <path> rev-parse. It will return 0 if the directory at <path> is a git repository and an error code otherwise.

Further Reading:

Upvotes: 56

user3108793
user3108793

Reputation: 11

Adding to @Walk's comments, git status will throw fatal message if its not a repo. echo $? will help to capture of its an ERROR or not. If its a git repo then echo $? will be 0 else 128 will be the value

Upvotes: 1

Walk
Walk

Reputation: 1649

We can also try git status command and if the output is like :

fatal: Not a git repository (or any of the parent directories): .git

Then, the directory is not a git repository.

Upvotes: 6

Simon Clarkstone
Simon Clarkstone

Reputation: 300

Any directory in the system could be a git working copy. You can use an directory as if it contained a .git subdirectory by setting the GIT_DIR and GIT_WORK_TREE environment variables to point at an actual .git directory and the root of your working copy, or use the --git-dir and --work-tree options instead. See the git man page for more details.

Upvotes: 3

Related Questions