我正在尝试使过程自动化并发出git branch
命令以找出我所在的分支。除了新初始化的存储库git branch
什么都不返回以外,其他一切都工作正常。鉴于我对仓库没有做任何事情,甚至没有执行最初的提交,我都可以接受答案。但是,如果我运行git status
它,它会告诉我我在master
分支上,如下所示:
$ mkdir todelete $ cd todelete $ git init Initialized empty Git repository in /u/u70021a/todelete/.git $ git status On branch master No commits yet nothing to commit (create/copy files and use "git add" to track) $ git branch $
难道我做错了什么?有没有我没有正确设置的设置?
我对Git也有很多新人,我无法向他们解释为什么显示他们所在的分支的命令什么都没显示,而status命令却显示。
I upvoted two other answers, but I think the way to think of this is simple: You can be on a branch that doesn't exist. That's normal in a new empty repository, too, because for a branch name to exist, that branch name must identify the hash ID of an existing, valid commit. A new empty repository has no commits, so no branch names are allowed to exist yet.
Nonetheless, you are, initially, on some branch. The branch you are on is the one whose name is stored in the special name HEAD
. In a new, empty repository, Git stores the name master
(more precisely, refs/heads/master
—the full name of the branch) in HEAD
, so you are on master
, while master
does not exist.
You can change which non-existent branch you are on using git checkout -b
:
$ git init Initialized empty Git repository in [path] $ git checkout -b asdf Switched to a new branch 'asdf' $ git checkout -b hello Switched to a new branch 'hello'
Whenever you are on a branch that does not exist, the next commit you make creates the branch. This is also how git checkout --orphan
works.
git branch
什么都不显示,因为没有分支。但是,您可以阅读man git init
:
This command creates an empty Git repository - basically a .git directory with subdirectories for objects, refs/heads, refs/tags, and template files. An initial HEAD file that references the HEAD of the master branch is also created.
I bolded the part I think is relevant - it looks like although there is no master branch yet, a reference to it already exists and that is why it is shown in git status
. A proper branch will be created upon committing.
现有的答案解决了字面上的问题,即输出为何如此,但我认为它们已经掩盖了实际问题...
您说您正在自动化某件事,所以我建议在脚本上下文中最好的工具git status
也不git branch
是。
在此讨论中可以找到一些替代方法:如何以编程方式确定当前已签出的Git分支
在不知道您的需求(或您希望未出生分支的行为方式)的情况下,我不一定会提出建议,但我的意思是,有些命令是用于人机交互(瓷器)的,而有些则是用于脚本的(管道)
该分支尚未诞生。因此git branch
,不显示它(git symbolic-ref HEAD
表示您的HEAD指向默认的分支主机,并且由于git branch
未显示而未出生,也就是说,您可以位于尚不存在的分支上)。但是,提交某些内容将创建分支。
如果签出orphan
分支,情况也是如此。
我想git status
显示分支名称,因为这是将要创建的分支。
有关脚本的信息,请参见如何以编程方式确定当前已签出的Git分支