git: a quick command to go to root of the working tree

Viewed 31599

I wanted a simple git command to go up to the "root" of the repository.

I started with a script, but figured that I cannot change active directory of the shell, I had to do a function. Unfortunately, I cannot call it directly with the non-dash form "git root", for instance.

function git-root() {
 if [ -d .git ]; then
  return 0
 fi

 A=..
 while ! [ -d $A/.git ]; do 
  A="$A/.."
 done
 cd $A
}

Do you have a better solution? (the function has been written quickly, suggestions are welcome)

8 Answers

Peter's answer is the master reply. Many others observed that it doesn't work if you're already in the git root directory, unfortunately their solutions are overwhelming complex.

Here my one-liner:

alias cd-gitroot='cd $(git rev-parse --show-cdup)/.'
Related