Search code examples
gitbashcd

How do I cd to the closest parent folder that has a .git folder with bash?


When working on projects that are version controlled I often end up in a nested folder. Using cd ../../ gets a bit cumbersome, so I was wondering if there is a way to define an alias in bash that cd's to the parent until it reaches a folder with a .git folder, or it reaches ~.

So let's say that

  • ~/my-project is a git repository
  • my cwd is ~/my-project/deeply/nested/folder/structure
  • I run the command and am cd'ed to ~/my-project

What command could do this? Would I need a bash function?


Solution

  • The command you're looking for is git rev-parse --show-toplevel, you can make a bash function that uses it.

    gr() {
        cd "$(git rev-parse --show-toplevel)"
    }
    

    I also have in my ~/.gitconfig:

    [alias]
        root = rev-parse --show-toplevel
    

    Which makes this command a little more reasonable looking.