从不同的目录执行 git pull

72

我正在配置calimoucho(一个小型持续集成服务器),为了使其工作,我需要运行一个命令从其外部拉取克隆的git hub存储库。

更准确地说,我将通过示例来解释:

我有以下存储库:

cd /home/sas
mkdir apps
cd apps
mkdir myApp
cd myApp
git init
echo "my file" > file
git add .
git commit -m "initial commit"

这只是一个愚蠢的测试存储库,我的应用程序应该在其中。

现在我需要将该存储库克隆到检出文件夹。

cd /home/sas
mkdir calimoucho
cd calimoucho
mkdir checkout
cd checkout
git clone /home/sas/apps/myApp/ 

所以我有以下目录结构

~/apps
    myapp
      .git
      file
~/calimoucho
    checkout
      myapp
        .git
        file
持续集成服务器需要从~/apps/myapp获取新的更改,然后在~/calimoucho/checkout/myapp执行一条命令行语句,该语句需要在~/calimoucho中运行。 我尝试使用以下命令。
~/calimoucho$ git --git-dir=/home/sas/apps/myApp/.git --work-tree=/home/sas/calimoucho/checkout/myApp/ pull

然后我收到了以下错误

fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.

如果我不指定--work-tree选项,那么pull命令会被执行,但更改将应用到~/calimoucho文件夹而不是~/calimoucho/checkout/myApp文件夹。有什么办法可以从~/calimoucho文件夹更新克隆的代码库吗?

非常感谢。


已经检查了这个问题:http://stackoverflow.com/questions/7188314/git-directory-and-working-directory - opensas
6个回答

134

我也有这个问题。我在git文档(https://git-scm.com/docs/git)中找到了答案。

运行命令:

git -C <git-working-directory> pull <git remote>

回答这个问题的具体命令是

git -C checkout/myApp/ pull

请注意,重要的是在pull命令之前使用-C <git-working-directory>,而任何其他的pull选项可以在命令的末尾指定。在上面的示例中,git clone命令将设置默认的远程存储库~/apps/myapp,因此无需指定远程存储库。


15

git -C ~/Documents/blar/blar/directory/ pull

在经过数小时的搜索后,这个命令对我非常有效。我是在Mac终端中执行的。


2
这个回答并没有为@Danny已经提供的答案增加任何内容。 - blthayer
同样是在Ubuntu 22上,使用常规的bash shell,我也无法成功使用git-dir=选项,但用-C选项却一次性成功了。 - Frank N

7
这个对我有效:
git --git-dir=/home/myuser/awesomeproject/.git --work-tree=/home/myuser/awesomeproject pull

我正在使用它在post-update钩子中自动拉取和重启我的测试服务器上的pm2。


1
--git-dir does more than that. -C is a better option. From manual page for Git: If you just want to run git as if it was started in <path> then use git -C <path>. - Ruslan Gunawardana
你好,我几年前为这篇文章投了票,但当我重新使用这个命令时,我意识到它的工作方式不同了。我在 git 操作中使用它,我的 git head 已经更新,但没有文件被更改,我必须运行一个 hard 命令才能获取 . 中的更改。我认为只有在项目文件夹中才应该使用 dir,但是 .git 在另一个文件夹中。 - Pascal de Sélys

4
在我的情况下,这是唯一有效的解决方案:
git --git-dir=/gitbackup/test/.git pull

这个并没有按照预期工作。它会将更改拉入.git,但不会覆盖和更新项目文件,这是从git pull中预期的行为。你会发现一个git log显示了新的提交,但是在项目目录中有一堆明显未提交的更改,这些更改是旧版本的文件与新提交进行比较的结果。 - Brettins

1

不应将工作树设置为与git-dir变量不同的存储库。我认为当您不希望.git文件夹与您的工作树位于同一目录中时,它们应该被使用。相反,请尝试以下操作:

~/calimoucho/$ git pull --work-tree=checkout/myApp/  ../../apps/myapp

我尝试了一下,结果是:sas@test:~/calimoucho$ git pull ../apps 致命错误:不是git仓库(或任何父目录):.git(也尝试过../apps/myApp、../apps/myApp/.git) - opensas
1
啊!这就是问题所在,站在克隆的存储库文件夹里一切都正常(事实上,一个简单的“git pull”可以正常工作)...问题是如何从另一个文件夹中执行它... - opensas
--work-tree 不应该放在 pull 命令之前吗?像这样:git --work-tree=checkout/myApp/ pull ../../apps/myapp - Potherca

1

如果你的git版本不支持 git-working-directory 选项:

未知选项:-C

那么请先使用 push-directory 命令。

例如,这将从父目录中获取你的git项目(如果不存在,则克隆):

pushd ./project-name && git pull && popd || git clone https://repo-url/project-name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接