Run Git commands from outside a repository directory

There are multiple options to run a Git command from outside of a repository directory1. From least to most flexible, these are the --git-dir -C and --work-tree options.

--git-dir

Pass the --git-dir option pointing to the .git directory in the repository:

git --git-dir=/tmp/repository/.git log --format=oneline
6b5a4d9ed5346ec93c880c73eac43012eb9a809b Add sub/file.txt
37535441d4b3517a2362cde777af3d697acf5024 Add file.txt

-C

Much like changing directories2, the -C option runs the command as if if was run from within the repository.

git -C /tmp/repository/ log --format=oneline
13b6797244a57111f681ea16ade4b73196b1d68a Add sub/file.txt
6e3cb392609cb23e2185f3711cceb65f7e0ff085 Add file.txt

It can also point to a file or sub directory somewhere in the repository:

git -C /tmp/repository/sub log --format=oneline
669bf20cbb1103d9935ca8afd4a1a3678bd1de8d Add sub/file.txt
0a4af8f4f62b7c3d2c087aae565c86fcc6e95814 Add file.txt

--work-tree

The --work-tree option behaves like =--git-dir, but links to a directory in the working tree.

git --work-tree=/tmp/repository/ log --format=oneline
1cdfc73ffdf6601a77ace6bc2c9bda8f389902cd Add sub/file.txt
0a8fbe8f63f672f08509f36771d67d750bd322f9 Add file.txt

It can also point to a file or sub directory somewhere in the repository:

git --work-tree=/tmp/repository/sub log --format=oneline
fd3d2da957b7443dbe88fd243544a14d07369e3c Add sub/file.txt
77eab2288dba005018c9877bb404633f327beed9 Add file.txt
git --work-tree=/tmp/repository/sub/file.txt log --format=oneline
65efe2ec22836b020019ef8b5461a81de9e6a6f7 Add sub/file.txt
a1bec894dfd2ed9b2df9970bff6fc9111234c652 Add file.txt

You can even link to files that don’t exist, provided their containing directories do:

git --work-tree=/tmp/repository/does-not-exist.txt log --format=oneline
09581359f16a9e7ee0ecdc7121978ec513766e30 Add sub/file.txt
75206992e4ce68d5b23c70720290d4126a465d5c Add file.txt

  1. These are useful for when you need to get information about a repository you’re not currently in, but also for learning information about a file you don’t know the containing repository of. With -C, for example, you can list the commits for a file without first knowing the repository location:

    git --work-tree=/tmp/repository/sub log /tmp/repository/sub/file.txt
    
    ↩︎
  2. In fact, using the -C option is equivalent to switching directories in a subshell:

    (cd /tmp/repository && git log --format=oneline)
    
    01025361f1d1f39a550442642ffa0e1d32bc05ab Add sub/file.txt
    2d30004818ec1c54b0c11a7c3b0185af043ce5c2 Add file.txt
    
    ↩︎