git aliases operate in the wrong directory

Summary: the current working directory of commands run through git aliases is wrong.

The easiest way to demonstrate this is to have a git alias like so:

  • Change the name of a git repository on the local machine
  • File Level Tracking In Git (Files from multiple branches in same directory)
  • Why isn't tilde (~) expanding inside double quotes?
  • How to have git-svn take care of empty directories gracefully?
  • How to make SVN ADD ignore binaries
  • In BASH How Can One Recursively Copy Only Content Version-Controlled by Git?
  • [alias]
        pwd = !pwd

    So git pwd is just running the bash command pwd. One would think that the two commands’ outputs would be the same. Now, let’s try this out a few times:

    $ cd ~
    $ pwd && git pwd
    /home/limpchimp    # great!
    $ mkdir foo && cd foo && git init
    Initialized empty Git repository in /home/limpchimp/foo/.git/
    $ pwd && git pwd
    /home/limpchimp/foo  # great!
    $ mkdir bar && cd bar
    $ pwd && git pwd
    /home/limpchimp/foo   # uuhhhhhhhh...?

    It seems that git is changing the current working directory to be the first parent directory that has a .git folder (if one exists). This is very problematic; it’s screwing up certain scripts that I’ve written, which are meant to operate in a specific directory, and making me unable to use certain things as git aliases. Is there a way around this? How can I fix it?

  • Create revision per feature branch
  • fatal: Could not open file .git/rebase-merge/done for reading: No such file or directory
  • how do i use git namespaces locally?
  • NGit making a connection with a private key file
  • Hartl's Ruby on Rails / Hello_App / Heroku Error H10
  • Applying git commits to working tree unadded?
  • 2 Solutions collect form web for “git aliases operate in the wrong directory”

    This is clearly specified in the documentation as by design along with a workaround if needed.

    Git Config Alias

    Note that shell commands will be executed from the top-level directory
    of a repository, which may not necessarily be the current directory.
    GIT_PREFIX is set as returned by running git rev-parse –show-prefix
    from the original current directory

    This is a (mis?)feature, but you can work around it with $GIT_PREFIX as noted in this other stackoverflow question and answer:

    #! /bin/sh
    # script to do stuff in a git dir
    # since we're sometimes run from a git alias we need
    # to cd back into $GIT_PREFIX if it's set
    [ "$GIT_PREFIX" != "" ] && cd "$GIT_PREFIX"
    ... rest of script ...
    Git Baby is a git and github fan, let's start git clone.