24

I've seen this question, which tells how to get the path of a particular file relative to the root of the git repo. But I now want to get the path of the current directory, not a specific file. If I use

git ls-tree --full-name --name-only HEAD .

I get the list of all the files in the directory.

Is this possible?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
ewok
  • 20,148
  • 51
  • 149
  • 254
  • Are you looking for a way just to read the path? Is there a reason you don't want to use the `pwd` command? – Briana Swift Oct 07 '16 at 17:31
  • @BrianaSwift because I want the path relative to the root of the git repo, not the absolute path on the machine. For example, if I have a repo located at `/home/ewok/git/repo`, and `pwd` would print `/home/ewok/git/repo/src/java`, I want a command that will just give me `/src/java` – ewok Oct 07 '16 at 17:33

3 Answers3

45

How about:

$ git rev-parse --show-prefix

From man git-rev-parse:

--show-prefix
           When the command is invoked from a subdirectory, show
           the path of the current directory relative to the top-level
           directory.
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
0
#git ls-files --full-name  | xargs -L1 dirname | sort -u

Use that git rev-parse --show-prefix above, awesome

strobelight
  • 267
  • 2
  • 7
  • this gives me the current directory, but also all subdirectories recursively – ewok Oct 07 '16 at 17:34
  • actually, that's not quite right. sometimes it gives me the current directory, sometimes it gives me ONLY subdirectories. I can't figure out when it gives what – ewok Oct 07 '16 at 17:36
  • Is this better? git ls-files --full-name | head -1 | xargs -L1 dirname | sort -u – strobelight Oct 07 '16 at 17:38
  • nope. now it only gives 1 directory, but it doesn't seem to be consistent in which directory it gives. – ewok Oct 07 '16 at 17:40
  • `git rev-parse --show-prefix` is one command I'll put in my toolbelt. – strobelight Oct 07 '16 at 18:01
0

Adding onto the great answer from Arkadiusz Drabczyk, I just wrapped the suggested command in a shell script (calling it rd.sh, standing for "relative directory" or "repository directory"), and make it print "/" if the git rev-parse --show-prefix command would return nothing (at the top level). I'm just starting to use this now, so we'll see how it works!

#!/bin/bash
# rd.sh: shows the "repository directory" rather than the entire absolute dir from 'pwd'

RELATIVE_DIR=`git rev-parse --show-prefix`

if [ -z "$RELATIVE_DIR" ]; then
  echo "/"
else
  echo $RELATIVE_DIR
fi
Peter W
  • 952
  • 8
  • 18