如何在不在存储库中的情况下执行Git命令?

时间:2011-08-22 15:42:56

标签: git

有没有办法在没有存储库的情况下对存储库执行Git命令?

例如:git /home/repo log

请不要告诉我cd。我是通过exec电话来做的。

6 个答案:

答案 0 :(得分:148)

使用-C选项(docs):

git -C /home/repo log

几乎等同于--git-dir--work-tree而没有追加通常的.git文件夹

修改

回答downvoted ......非常惊人,严格来说,这是这个问题的唯一正确答案。某些选项--git-dir--work-tree不存在从工作树外部访问存储库,它们用于将.git移动到其他地方,并且在某些地方使用它们要复杂得多例。

例如,仅获取/home/repo/subdir的日志:

git -C /home/repo/subdir log .

git -C /home/repo log subdir

log .--git-dir无法使用--work-tree。必须处理路径以提取相对于工作树顶部的子路径,即使在这种情况下,如果不使用--选项,git也不会将其识别为路径,因此唯一可行的方法是:

git --git-dir /home/repo/.git log -- subdir

此外,--work-tree与我的版本(git 1.9.1)的log子命令完全不兼容。它被忽略了:

git --git-dir /home/repo/.git --work-tree /home/repo/subdir log -- subdir
git --git-dir /home/repo/.git --work-tree /home/repo/whatever log -- subdir

我甚至不知道这是一个错误还是一个功能......与许多git设计选择一样。

答案 1 :(得分:65)

尝试:

git --git-dir=/home/repo/.git log

将路径一直提供到存储库的.git目录非常重要。否则,您将只收到类似以下内容的错误消息:

fatal: Not a git repository

答案 2 :(得分:17)

实际上你需要一起使用--git-dir和--work-tree。这是一个例子:

local [] Desktop: mkdir git
local [] Desktop: cd git
local [] git: touch README.txt
local [] git: git init
Initialized empty Git repository in /Users/albert/Desktop/git/.git/
local [] git: cd ..
local [] Desktop: git --work-tree=git --git-dir=git/.git add .
local [] Desktop: git --work-tree=git --git-dir=git/.git commit -a -m 'initial commit, called from outside the git directory'
[master (root-commit) ee951b1] initial commit, called from outside the git directory
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.txt
local [] Desktop: cd git
local [] git: git log --pretty=oneline
ee951b161053e0e0948f9e2a36bfbb60f9c87abe initial commit, called from outside the git di

答案 3 :(得分:6)

我已多次尝试过! 我终于明白了!

git -C dir --no-pager log --format='%an' -1 filename

请记住,请不要将.git添加到您的

  

-C dir

答案 4 :(得分:4)

对于任何git命令,您都可以执行以下操作:

git --git-dir=<PATH-TO-REPO>/.git --work-tree=<PATH-TO-REPO> <git-command>

例如,如果要执行git状态:

 git --git-dir=/home/myrepo/.git --work-tree=/home/myrepo/  status

或者如果您要检查存储库中的分支:

git --git-dir=/home/myrepo/.git --work-tree=/home/myrepo/  rev-parse --abbrev-ref HEAD

答案 5 :(得分:2)

这与@max的答案类似。不幸的是, - git-dir并没有做我需要的事情。 编辑回想起来,使用--work-tree建议的另一个[上一页]回答建议。我不确定使用环境或标志是否更合适,所以我会留下我的答案以防有人在其中使用,但我会转而使用--work-tree / {{ 1}}。

有两个回购,一个在另一个内,但不是子模块;外部回购忽略它:

--git-dir

我想要的是tools (outer repo) gcc/4.9.2 (inner repo) 相对于外部回购的输出。这就是我提出的内容(bash语法;为了便于阅读而分割为多行):

git rev-parse --show-prefix

从4.9.2内执行时,它会生成字符串prefix_dir=$(cd ..; git rev-parse --show-toplevel) prefix_dir=$(GIT_WORK_TREE=${prefix_dir} git rev-parse --show-prefix)