git pull while not in a git directory

Let's say I have a directory, /X/Y , which is a git repository. Is it possible to somehow call a command like git pull from inside /X , but targeting the /X/Y directory?

EDIT: I guess I was wondering specifically: is it possible to do this using the a git command, but without having to change directories?

NOTE: I've accepted VonC's answer as it's much more elegant than previous options. For people running Git older than 1.8.5, please see bstpierre's answer below.


Starting git 1.8.5 (Q4 2013), you will be able to "use a Git command, but without having to change directories".

Just like " make -C <directory> ", " git -C <directory> ... " tells Git to go there before doing anything else .

See commit 44e1e4 by Nazri Ramliy :

It takes more keypresses to invoke Git command in a different directory without leaving the current directory:

  • (cd ~/foo && git status)
    git --git-dir=~/foo/.git --work-tree=~/foo status
    GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status
  • (cd ../..; git grep foo)
  • for d in d1 d2 d3; do (cd $d && git svn rebase); done
  • The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.

    With this new option, the above can be done with fewer keystrokes:

  • git -C ~/foo status
  • git -C ../.. grep foo
  • for d in d1 d2 d3; do git -C $d svn rebase; done

  • Since Git 2.3.4 (March 2015), and commit 6a536e2 by Karthik Nayak ( KarthikNayak ), git will treat " git -C '<path>' " as a no-op when <path> is empty.

    ' git -C "" ' unhelpfully dies with error " Cannot change to '' ", whereas the shell treats cd ""' as a no-op.
    Taking the shell's behavior as a precedent, teach git to treat -C ""' as a no-op, as well.


    Edit :

    There's either a bug with git pull , or you can't do what you're trying to do with that command. You can however, do it with fetch and merge:

    cd /X
    git --git-dir=/X/Y/.git fetch
    git --git-dir=/X/Y/.git --work-tree=/X/Y merge origin/master
    

    Original answer :

    Assuming you're running bash or similar, you can do (cd /X/Y; git pull) .

    The git man page specifies some variables (see "The git Repository") that seem like they should help, but I can't make them work right (with my repository in /tmp/ggg2):

    GIT_WORK_TREE=/tmp/ggg2 GIT_DIR=/tmp/ggg2/.git git pull
    fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
    

    Running the command below while my cwd is /tmp updates that repo, but the updated file appears in /tmp instead of the working tree /tmp/ggg2:

    GIT_DIR=/tmp/ggg2/.git git pull
    

    See also this answer to a similar question, which demonstrates the --git-dir and --work-tree flags.


    你可以把它包装在一个bash脚本或git别名中:

    cd /X/Y && git pull && cd -
    
    链接地址: http://www.djcxy.com/p/18872.html

    上一篇: git仓库应该在哪里创建?

    下一篇: git pull而不在git目录中