Getting and Parsing the Repository Root Using Git

August 15, 2019

git rev-parse --show-toplevel

Will print the full, absolute path for a git repo. This can be passed into sed for further processing. For instance:

export p="/Users/brettneese/Development/git/github.com/brettneese/testdir/sub/test.txt"
export GIT_PATH=$(git rev-parse --show-toplevel)
echo $p | sed "s:^${GIT_PATH}::" | cut -c 2-

# sub/test.txt

And, of course:

cd "/Users/brettneese/Development/git/github.com/brettneese/testdir/sub/"
echo ${PWD} | sed "s:^$(git rev-parse --show-toplevel)::" | cut -c 2-

# sub

This is useful for auto-committing, and such.

h/t baudtack