views:

244

answers:

2

I wanted a simple git command to go up to the "root" of the repository.

I started with a script, but figured that I cannot change active directory of the shell, I had to do a function. Unfortunately, I cannot call it directly with the non-dash form "git root", for instance.

function git-root() {
 if [ -d .git ]; then
  return 0
 fi

 A=..
 while ! [ -d $A/.git ]; do 
  A="$A/.."
 done
 cd $A
}

Do you have a better solution? (the function has been written quickly, suggestions are welcome)

+2  A: 

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
}
jleedev
+8  A: 

This has been asked before, here. 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)'
Peter
Put that in jleedev's wrapper function and you're done.
Dennis Williamson
just use an alias. (see edit).
Peter
why not using git's alias mechanism?
kaizer.se
I guess that would be fine too :)
Peter