Juicy lil' bytes

How to Determine if a Directory Has Been Initialized With Git

Has git init been run on the directory? Here’s how you find out.

Git initialization of an existing directory with the command git init results in a subdirectory that is named .git. It contains your git goodies. To determine whether the directory has been git initialized, simply check for the presence of the .git subdirectory. Here’s how to do it with C or C++:

Git or No Git?
1
2
3
4
5
6
7
8
9
10
#include <sys/stat.h>
struct stat sb;
const char * pathname = ".git";
if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
{
    // .git directory is present so initialization has occurred, do git stuff in this block
}
else {
  // .git initialization has not occurred, handle that here
}

Directory Exists in Other Languages

Trying to do this in another language? A quick search for “directory exists” in your language du jour generally leads to the information that you need.

Here is how you determine whether a directory exists in JavaScript, PHP, Python, and Ruby.