27

Possible Duplicate:
Is there a way to get to the git root directory in one command?

Sometimes, I'm confused with git thinking that I'm inside a Git working dir, but it's not obvious to me what the top-level working directory (containing .git/) is. (Probably, that repo was created by a mistake.)

So, how do I find out the top-level Git repo directory if I'm somewhere inside the subdirectories? How do I ask git to print what it thinks the current top-level working directory is?

Community
  • 1
  • 1
imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104

2 Answers2

54

Try this:

git rev-parse --show-toplevel
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • 1
    Thanks for pointing this out; without your help, it'd be hard for me to guess to look into `git-rev-parse` -- because of its name suggesting it's about processing revision specifications. BTW, I'd be glad to see `git --work-tree` work similar to `git --exec-path[=]`: "If no path is given, git will print the current setting"; at least, IMO, it'd be a logical place to look for such a feature. – imz -- Ivan Zakharyaschev Jul 19 '11 at 13:55
  • 1
    **Note** that this fails if inside the `.git` directory. See the marked duplicate for a solution. – Tom Hale Aug 10 '16 at 06:09
  • This command also does not work from a submodule – Nik Reiman Aug 18 '16 at 08:50
  • the name that is returned from the --show-toplevel flag; can this be changed?? I have a mapped network drive I did the git init on and now when I am actually on the server (not on the mapped side of it) the drive names are different. Meaning what gets returned on the --show-toplevel is not correct when I am on the server. It needs to return D:/ rather than Y:/ this is what I can't find how to do – Coty Embry Dec 30 '16 at 19:16
  • 1
    @CotyEmbry Perhaps [`git rev-parse --show-cdup`](https://git-scm.com/docs/git-rev-parse#git-rev-parse---show-cdup) will better suit you. Anyway, that's strange that the absolute path reported on your server is not correct... – imz -- Ivan Zakharyaschev Oct 26 '17 at 03:05
2

I've written a simple script (git-find-git-dirs in my "git-shortcuts" collection) to make such queries to Git handy:

#!/bin/bash

# find-git-dirs -- A simple script to "find" (i.e., "print") the GIT_DIR, as assumed by Git. (Useful if you are in a subdir, and you are not sure about the top-level repo dir.)

SUBDIRECTORY_OK=yes
. "$(git --exec-path)/git-sh-setup"

echo "GIT_DIR=$GIT_DIR"

and put it to ~/bin/; now I can do my simple query like this:

$ git find-git-dirs
GIT_DIR=/home/imz/.git
GIT_WORK_TREE=
$ 

The only thing I lack from the initial question is the printing of the top-level working dir, now it just prints the path to the internal git repo dir...

imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104