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

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


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.


I think the answer you already have is good (and possibly more efficient) but a basic way of achieving this would be to use a loop:

until [ -d .git ]; do cd ..; done

That is, move into the parent directory until the directory .git exists.

To protect against an infinite loop if you run the command from outside of a git repo, you could add a basic check:

until [ -d .git ] || [ "$PWD" = "$p" ]; do p=$PWD; cd ..; done

I'm not sure how portable it is, but on my system I have a variable $OLDPWD which can be used instead:

until [ -d .git ] || [ "$PWD" = "$OLDPWD" ]; do cd ..; done


Again, already answered, but I have a script as follows that does essentially that:

#!/bin/bashfilename=$1[[ ! ${filename} ]] && echo "no filename" && exit -1path=$(pwd)while [[ "${path}" != "" && ! -e ${path}/${filename} ]]; do   path=${path%/*}done[[ "${path}" == "" ]] && exit -1;cd ${path}

where you would do findup .git (which in turn could be turned into an alias)