Reputation: 308
I recently discovered that setting the $GIT_DIR
environment variable or using the --git-dir
tag in a command will let you specify a git repository to run that command in. That means that you can have two different .git
directories in a directory tree, rename them to something else if you want, and still be able to use whichever one you like.
One catch is that the directory you are currently in will be treated as your working directory. If you want to enter git commands from a subdirectory or even a directory that's not even in your working tree, you can specify the working directory to use with the --work-tree
flag or $GIT_WORK_TREE
environment variable.
This opens up a lot of possibilities. For example, you could have a git repo in your home directory for your dotfiles, and still have other git repos in subdirectories for other work.
Is there a reason that this is not done more often? Is this sort of thing recommended?
Upvotes: 2
Views: 83
Reputation: 489323
As chepner answered, it is useful, it's just a bit (or a lot) of a pain in the butt, as you yourself noted, since you must also set $GIT_WORK_TREE
or use --work-tree
in various cases. You also have the issue that there is only a single staging area, $GIT_DIR/index
, for each repository, regardless of the work-tree. You can override this as well by setting $GIT_INDEX_FILE
.
(The next part is going in a different direction than you are; I include it for completeness.)
In older versions of Git there is a script that tries to make this easier, and in Git version 2.5, the script was (mostly) replaced with a new command, git worktree
, that lets you add explicit separate work-trees (each of which is meant to be on a different branch, with checking to make sure it stays that way). Git knows how to deal with these automatically, and takes care of the --git-dir
, --work-tree
, and separate index files for you, also automatically. But there are some bugs in it, with ongoing fixes; I would not recommend using this until at least Git version 2.6, and preferably 2.9 or whatever the latest is now, if you're going to use it heavily.
Upvotes: 2
Reputation: 531948
The ability to change the working directory makes it easy to have multiple working directories for the same repository. This is useful, for example, if you are working on two branches at once (say, a regular development branch and a bugfix branch).
Trying to share the same working directory for multiple repositories is problematic because it is unlikely that two commits can share a single working directory.
Upvotes: 1