Getting and Parsing the Repository Root Using Git

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/"
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/"
echo ${PWD} | sed "s:^$(git rev-parse --show-toplevel)::" | cut -c 2-

# sub

This is useful for auto-committing, and such.

h/t baudtack

Show Comments