2

Since the git command can be run from any subdirectory of the repo, or even from outside the directory hierarchy of the repo, I'm looking for a git command that'll show me the location of the repo. Essentially, parent directory of the repo's .git/ directory.

For example, if I have a directory structure as follows, I want the output of the command to be /Users/gurjeet/dev/project_repo/, for all the commands shown after the sample directory tree.

/Users/gurjeet/
├── some_directory/
└── dev/
    └── project_repo/
        ├── .git/
        └── src/
$ cd /Users/gurjeet/dev/project_repo
$ git --where-is-.git

$ cd /Users/gurjeet/dev/project_repo/src
$ git --where-is-.git

$ cd /Users/gurjeet/dev/
$ export GIT_DIR='/Users/gurjeet/dev/project_repo/src'
$ git --where-is-.git

$ cd /Users/gurjeet/dev/
$ export GIT_DIR='/Users/gurjeet/dev/project_repo/src'
$ git --where-is-.git

$ cd /tmp
$ export GIT_DIR='/Users/gurjeet/dev/project_repo/src'
$ git --where-is-.git
Gurjeet Singh
  • 2,635
  • 2
  • 27
  • 22

1 Answers1

3

I believe what I was looking for is provided by git rev-parse --absolute-git-dir, or more accurately by the following command:

$ dirname $(GIT_DIR=~/dev/POSTGRES/.git git rev-parse --absolute-git-dir)

A few sample runs:

$ cd ~/dev/Q.HT/public/quote_of_the_day
$ dirname $(GIT_DIR=~/dev/POSTGRES/.git git rev-parse --absolute-git-dir)

/Users/gurjeet/dev/POSTGRES

$ cd ../../../POSTGRES/
$ dirname  $(GIT_DIR=~/dev/POSTGRES/.git git rev-parse --absolute-git-dir)

/Users/gurjeet/dev/POSTGRES

$ cd src
$ dirname  $(GIT_DIR=~/dev/POSTGRES/.git git rev-parse --absolute-git-dir)

/Users/gurjeet/dev/POSTGRES

Some Google foo lead me to Get the path where git alias was run from, which lead me to read git rev-parse --help, which had all the info I needed.

Gurjeet Singh
  • 2,635
  • 2
  • 27
  • 22
  • 1
    Note that `--absolute-git-dir` is relatively new; on old versions of Git, use `--git-dir` and then feed that possibly-relative path through an absolute-path-expander such as `realpath`. This is tricky since not all systems have usable absolute path expanders such as `realpath`, and those that do don't always call it `realpath`. :-) – torek Aug 13 '21 at 22:30
  • Thanks @torek! In a few quick tries, I could not get the `--git-dir` option to emit a relative path; it would emit only absolute paths for me. Would you mind sharing a setup where `--git-dir` emits a relative path rather than an absolute path. – Gurjeet Singh Aug 14 '21 at 16:08
  • I'm in my Git clone of Git (`/home/.../git`), and `git rev-parse --git-dir` simply outputs: `.git`. Using `--absolute-git-dir` I get `/home/.../git/.git`, as expected. If `$GIT_DIR` (env var) is set, `git rev-parse --git-dir` is equivalent to `echo $GIT_DIR`, provided `$GIT_DIR` is actually a valid Git directory: `GIT_DIR=./.git git rev-parse --git-dir` prints `./.git`. – torek Aug 15 '21 at 01:16