Git pulling depends on the current dir

ДМИТРИЙ МАЛИКОВ picture ДМИТРИЙ МАЛИКОВ · Mar 24, 2012 · Viewed 10.9k times · Source

I am trying to git pull some repository via root user from any directory.

For example, executing git pull from /root/:

#> cd ~
#> sudo -u dmalikov git --git-dir=/home/dmalikov/path/to/repo/.git pull 
/usr/libexec/git-core/git-sh-setup: line 142: cd: /root/.: Permission denied
Cannot chdir to /root/., the toplevel of the working tree

And executing git pull from /:

#> cd /
#> sudo -u dmalikov git --git-dir=/home/dmalikov/path/to/repo/.git pull 
Already up-to-date.

Why did current directory affects git pulling command?

How can that redundant cd be avoided?

Answer

amcnabb picture amcnabb · Mar 26, 2012

In your first example, the git command runs as user dmalikov with the current directory /root. Since the git pull command is equivalent to a git fetch followed by a git merge, and since git merge operates on the working tree, git tries to hunt for the working tree. As this user does not have permission to cd /root, the git command fails.

Even your second example doesn't work as you would expect. If there are actual changes to be pulled (instead of "Already up-to-date"), then the git pull will fail because it can't find the working tree.

You have a few simple options:

1) You can just do the git fetch portion of the operation by doing:

sudo -u dmalikov git --git-dir=/home/dmalikov/path/to/repo/.git fetch

which doesn't give any error for me.

2) You can add a cd to the working tree:

(cd /home/dmalikov/path/to/repo; sudo -u dmalikov git pull)