Check if path is a Git repository

TL;DR: To check if $PATH is a Git repository:

git -C $PATH rev-parse 2>/dev/null; echo $? # 0 = git repository


If you try to run a git command in a directory that’s not a repository, you’ll get:

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

So how can you tell if a directory is within a git repository?

You can get the exit status code ($?) from git commands like git status:

git status 2>/dev/null; echo $?

Exit code of 0 means it’s a git repository. Any other code (e.g., 128) means it’s not.

git rev-parse

For better performance and to specify a path, you can use git rev-parse:

git -C <path> rev-parse 2>/dev/null

Here’s an example of when the current working directory is not a git repository:

git -C . rev-parse 2>/dev/null; echo $?

Please support this site and join our Discord!