Why is “git branch” silent in new repositories?

天大地大妈咪最大 提交于 2020-01-11 06:41:13

问题


When you create a new repository and run git branch, it exits silently. For example:

$ mkdir /tmp/foo; cd /tmp/foo; git init
Initialized empty Git repository in /tmp/foo/.git/

$ git branch

Why doesn't the command provide any output, or show the master branch?


回答1:


TL;DR

No branch heads exist yet.

Detailed Explanation

A Git repository has no branches until you make your first commit. A newly-initialized repository sets HEAD to refs/heads/master, but refs/heads/master won't exist or contain a commit pointer until after the first commit is made.

During a commit, Git dereferences the symbolic-ref HEAD to find the head of the current branch, and then updates that head with the commit hash supplied by git-commit-tree.

The end result is that git branch has nothing to report in a new repository. With no branch heads present, it simply terminates silently with an exit status of zero.

See Also

  • git-branch(1)
  • git-commit-tree(1)
  • git-symbolic-ref(1).
  • git-update-ref(1)
  • gitcore-tutorial(7)



回答2:


Note that a branch is simply a pointer to a commit.
Since an empty repo (with its empty tree) has no commit, you have no branch.

A first commit will create a branch named 'master', because HEAD references refs/heads/master.
Should you want to create a first commit on a different branch (than master), you would need to change the symbolic ref of HEAD first (as detailed in this thread):

git symbolic-ref HEAD refs/heads/non-master 

And then make your first commit.




回答3:


Yes, you first need to perform

$ git add .
$ git commit -m 'first commit'

commands.



来源:https://stackoverflow.com/questions/11077919/why-is-git-branch-silent-in-new-repositories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!