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

This has been asked before, Is there a way to get the git root directory in one command? Copying @docgnome's answer, he writes

cd $(git rev-parse --show-cdup)

Make an alias if you like:

alias git-root='cd $(git rev-parse --show-cdup)'

Simpler still, steal from Is there a way to get the git root directory in one command? , and make an alias (as suggested by Peter) from

cd "$(git rev-parse --show-toplevel)"

This works whether you're in the root directory or not.


Peter's answer above works great if you're in a subdirectory of the git root. If you're already in the git root, it'll throw you back to $HOME. To prevent this, we can use some bash conditionals.

if [ "`git rev-parse --show-cdup`" != "" ]; then cd `git rev-parse --show-cdup`; fi

so the alias becomes:

alias git-root='if [ "`git rev-parse --show-cdup`" != "" ]; then cd `git rev-parse --show-cdup`; fi'

$ git config alias.root '!pwd'
$ git root

Unfortunately, changing your current directory can only be done by the shell, not by any subprocess. By the time git gets around to parsing your command, it's already too late -- git has already been spawned in a separate process.

Here's a really gross, untested shell function that just might do what you want:

function git() {
    if [ "$1" == "root" ]; then
        git-root
    else
        git "$@"
    fi
}