If you notice right after you've switched to master that you forgot to stage or commit some changes, you can just switch back immediately with git checkout b1
, of course, and then commit them.
However, you're right that it's very easy to commit changes on the wrong branch. Fortunately, git's branches are very lightweight - they're just a pointer to the tip of the branch in the commit graph - and git has good tools for rewriting the history so that it looks as you would like. Exactly what you'd need to do depends on the sequence of what you'd done, but there are lots of questions on Stack Overflow that deal with this. (Or you can just ask a new one if it's not clear.) Here's simple example:
... or if you'd done lots of commits on master that you suddenly realize are too controversial, and should be on a new topic branch you can do the following:
# Check that git status is clean and you really are on the master branch:
git status
# Create a branch based on your current position:
git branch controversial
# Move master back to the last non-controversial commit, making
# sure that the working tree and index match:
git reset --hard <NON-CONTROVERSIAL-COMMIT>
If there were already lots of commits on your existing branch b1
, then you could cherry-pick those from master:
# Switch back to `b1`:
git checkout b1
# Cherry-pick the commits that you'd rather were on b1:
git cherry-pick <CONTROVERSIAL-COMMIT-A>
git cherry-pick <CONTROVERSIAL-COMMIT-B>
# Switch back to `master`:
git checkout master
# Reset master back to the last non-controversial commit, making
# sure that the working tree and index match:
git reset --hard <NON-CONTROVERSIAL-COMMIT>
... of if you have lots of commits on master that should be on b1 you can use git rebase
.
In short, it's easy to recover from this kind of thing - you just have to understand what the commit graph looks like where you are, and what you'd rather it looked like.