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

Viewed 1362

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?

3 Answers
Related