在 git 中切换分支名称

可能有不止一种方法来问这个问题,所以这里有一个对这个问题的描述。我当时正在为 Master 工作,做了一些事情,然后决定暂时搁置这项工作。我备份了一些提交,然后从我开始我的垃圾工作之前的分支。实际上这个工作很好,我现在有一个不同的分支作为我的主要开发分支。我想知道我怎么能改变周围的事情,所以我工作的硕士再次,但它没有我的垃圾工作,并说工作是在另一个分支。

这个问题可以通过以下几种方式解决: 如何将主分支重命名为其他分支,然后再将其他分支重命名为主分支? 我如何备份 master,然后使所有已备份的提交都位于不同的分支上?

谢谢你的(快速)回答! 他们都很好。

47166 次浏览

This is relatively easy:

git checkout -b fake_master master # fake_master now points to the same commit as master
git branch -D master               # get rid of incorrect master
git checkout -b master real_master # master now points to your actual master
git checkout master                # optional -- switch on to your master branch

Start on master, create a branch called in-progress, then reset master to an earlier commit.

$ git branch in-progress
$ git reset --hard HEAD^

In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master:

git branch -m master crap_work
git branch -m previous_master master

I think you should consider a different development strategy to prevent issues like this. One that seems to work best for me is to never do development directly on my master branch. Regardless of the changes I'm making, I always create a new branch for new code:

git checkout -b topic/topic_name master

From there, I can push out the changes to public repositories:

git push pu topic/topic_name

or eventually just merge it back in with my master branch:

git checkout master && git merge topic/topic_name

If you truly need to go back to an older point in time and set that as your master, you can rename the current branch to something else and then check out an older version to be your master:

git branch -m master junk
git co -b master old_sha1_value

This will set your master to any point in one step:

git checkout -B master new_point