Check if Directory is Git Repository

Check if Directory is Git Repository

When working with Git from the command line, it can be useful to determine whether a directory belongs to a Git repository before running repository specific commands. This is particularly helpful in shell scripts and automation, where the current working directory may not always be known in advance. Checking the repository status first can prevent subsequent Git commands from failing when executed outside a repository. This tutorial explains how to check if directory is Git repository.

The git rev-parse command can be used to determine whether the current directory is inside a Git repository. Redirecting its error output makes it possible to use the command as a simple condition and print an appropriate message.

git rev-parse 2>/dev/null && echo 'Git repository' || echo 'Not Git repository'

A specific directory can also be checked without changing the current working directory by using -C option:

git -C /tmp/gitdemo rev-parse 2>/dev/null && echo 'Git repository' || echo 'Not Git repository'

Leave a Comment

Cancel reply

Your email address will not be published.