简体   繁体   English

如何在不提交更改的情况下移动到另一个分支?

[英]How to move to another branch without committing changes?

In my project I have branches a and b .在我的项目中,我有分支ab I'm working on a and want to switch over to working on a feature on b .我正在处理a并想切换到处理b上的功能。 However, my code in a is not in a state where it makes sense to make a commit.但是,我在a中的代码不在 state 中,在那里进行提交是有意义的。 Git won't allow me to just switch to b though. Git 不允许我切换到b How can I switch to b without committing on a ?如何在不提交a情况下切换到b

You can stash your changes:您可以存储您的更改:

git stash
git checkout b
git commit -am 'finish work on b'
git checkout a
git stash pop

switching to an existing branch losing changes can be done with git checkout followed by the --force flag可以使用git checkout后跟--force标志切换到现有分支丢失更改

git checkout YOUR_BRANCH_NAME --force

Use a temporary branch to carry the changes over使用临时分支来进行更改

You are currently on branch a and have some uncommitted changes.您当前在分支a上并且有一些未提交的更改。 Let's create a branch and commit those changes to that branch.让我们创建一个分支并将这些更改提交到该分支。 git branches are cheap. git分支很便宜。 Create them as often as you want, delete them when you're done.随心所欲地创建它们,完成后删除它们。

git checkout -b a-temp
git add .
git commit

This creates and switches to a new branch, a-temp .这将创建并切换到一个新分支a-temp Your temporary changes get committed to a-temp .您的临时更改将提交给a-temp a remains unchanged. a保持不变。 Now, let's switch to b and try to cherry-pick them:现在,让我们切换到b并尝试cherry-pick它们:

git checkout b
git cherry-pick a-temp

A successful cherry-pick adds a commit to b , that has the former-uncommitted changes.一个成功的cherry-pick 向b添加了一个提交,它具有以前未提交的更改。 Let's un-commit them again:让我们再次取消提交它们:

git reset HEAD^

Now, they're no longer commit, and b is what it was.现在,他们不再提交,而b就是它原来的样子。 The originally-uncommitted changes are still uncommitted.最初未提交的更改仍然未提交。

A failed cherry-pick indicates that the uncommitted changes conflict with the b branch.一个失败cherry-pick表示未提交的更改与b分支冲突。 You're on your own to figure why;你自己去弄清楚为什么; but, first, let's unwind and go back to the previous status quo.但是,首先,让我们放松一下,让 go 回到之前的状态。

git cherry-pick --abort
git checkout a
git cherry-pick a-temp      # guaranteed to work, since a-temp branched off a
git reset HEAD^

Now you're back on a , with the same uncommitted changes.现在您又回到a ,具有相同的未提交更改。 You can take your time figuring out the reason for the merge conflict, and what you need to do about it.您可以花时间找出合并冲突的原因,以及您需要做些什么。

In all cases, let's delete the temporary branch so you can try this trick again, later:在所有情况下,让我们删除临时分支,以便稍后您可以再次尝试此技巧:

git branch -D a-temp

This approach is a little bit more work than use the stash, but is a little bit safer in case of a merge conflict.这种方法比使用存储多一点工作,但在合并冲突的情况下更安全一些。 Too often I confused git stash pop with git stash drop , and had to do some cleanup.我经常混淆git stash popgit stash drop ,不得不做一些清理工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM