How do I connect to the closest parent folder with a .git folder with bash?

When working on version controlled projects, I often end up in a subfolder. Usage is cd ../../

getting a little cumbersome, so I was wondering if there is a way to define an alias in bash that cd for the parent until it reaches the folder with the folder .git

or it reaches ~

.

So let's say that

  • ~/my-project

    is the git repository
  • my cwd ~/my-project/deeply/nested/folder/structure

  • I run the command and I cd'ed up ~/my-project

Which team can do this? Do I need a bash function?

+3


source to share


3 answers


The command you are looking for is git rev-parse --show-toplevel

, you can use the bash function that uses it.

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

      

I also have mine ~/.gitconfig

:



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

      

This makes this command a little smarter.

+7


source


I think the answer you already have is good (and arguably more efficient), but the main way to achieve this would be to use a loop:

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

      

That is, change to the parent directory until the directory exists .git

.

To protect against an infinite loop, if you run a command from behind a git repo, you can 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

that can be used instead:

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

      

+3


source


Again, already answered, but I have a script as follows from the fact that:

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

      

where would you do findup .git

(which in turn could be turned into an alias)

0


source







All Articles