Can I store the .git folder outside the files I want tracked?

You just need to ensure that the repository knows where the work tree is and vice versa.

To let the repository know where the work tree is, set the configuration value core.worktree. To let the work tree know where it’s git directory is, add a file named .git (not a folder!) and add a line like

gitdir: /path/to/repo.git

Since git 1.7.5 the init command learned an extra option for this.

You can initialize a new separate repository with

git init --separate-git-dir /path/to/repo.git

This will initialize the git repository in the separate directory and add the .git file in the current directory, which is the working directory of the new repository.

Previously to 1.7.5 you had to use slightly different parameters and add the .git file yourself.

To initialize a separate repository the following command links the work-tree with the repository:

git --git-dir=/path/to/repo.git --work-tree=. init && echo "gitdir: /path/to/repo.git" > .git

Your current directory will be the working tree and git will use the repository at /path/to/repo.git. The init command will automatically set the core.worktree value as specified with the --git-dir parameter.

You could even add an alias for this:

[alias]
    initexternal = !"f() { git --work-tree=. --git-dir=\"$1\" init && echo \"gitdir: $1\" >> .git; }; f"

Use git version control on a read-only working directory

With the knowledge above, you can even set up git version control for an working directory without having write permissions. If you either use --git-dir on every git command or execute every command from within the repository (instead of the working directory), you can leave out the .git file and therefore do not need to create any files within the working directory. See also Leos answer

Leave a Comment