In my project I have branches a
and b
. I'm working on a
and want to switch over to working on a feature on b
. However, my code in a
is not in a state where it makes sense to make a commit. Git won't allow me to just switch to b
though. How can I switch to b
without committing on a
?
CodePudding user response:
You can stash your changes:
git stash
git checkout b
git commit -am 'finish work on b'
git checkout a
git stash pop
CodePudding user response:
switching to an existing branch losing changes can be done with git checkout
followed by the --force
flag
git checkout YOUR_BRANCH_NAME --force
CodePudding user response:
Use a temporary branch to carry the changes over
You are currently on branch a
and have some uncommitted changes. Let's create a branch and commit those changes to that branch. git
branches are cheap. 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
. Your temporary changes get committed to a-temp
. a
remains unchanged. Now, let's switch to b
and try to cherry-pick
them:
git checkout b
git cherry-pick a-temp
A successful cherry-pick adds a commit to b
, that has the former-uncommitted changes. Let's un-commit them again:
git reset HEAD^
Now, they're no longer commit, and b
is what it was. The originally-uncommitted changes are still uncommitted.
A failed cherry-pick
indicates that the uncommitted changes conflict with the b
branch. You're on your own to figure why; but, first, let's unwind and go back to the previous status quo.
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. 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.