5

I want to add and commit a file in git without changing my current working directory. Is this possible?

> pwd
/tmp 

> git --git-dir=/tmp/git_test/.git init
Initialized empty Git repository in /tmp/git_test/.git/

> ls /tmp/git_test
commit1

> git --git-dir=/tmp/git_test/.git add /tmp/git_test/commit1
fatal: '/tmp/git_test/commit1' is outside repository

> git --git-dir=/tmp/git_test/.git add commit1
fatal: pathspec 'commit1' did not match any files

(git add -A seems to use the current working directory, rather than the argument to --git-dir)

dnw
  • 143
  • 9
  • It may be "cheating", but running `(cd /tmp/git-test; git add commit1)` will leave your outer shell in the same directory it had been before spawning the subshell which runs everything within `(...)`. – Charles Duffy Mar 21 '12 at 01:25
  • Answered elsewhere on Stack Overflow:http://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected – dnw Mar 21 '12 at 01:25

1 Answers1

13

You missed an option: --work-tree. If you're outside the repository, you need to supply both that and --git-dir:

--work-tree=<path>

Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git-config(1) for a more detailed discussion).

Community
  • 1
  • 1
Cascabel
  • 479,068
  • 72
  • 370
  • 318
  • if this is the right answer, please give @Jefromi the credit and mark ("check") it as the correct answer. – Flak DiNenno Apr 09 '14 at 20:37
  • 1
    @FlakDiNenno Educating new users is certainly good, but this question is two years old and the OP hasn't been seen in a year and a half. – Cascabel Apr 09 '14 at 21:07