WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the master branch checked out.
So how I achieve this goes like this:
git commit the changes right away with a good commit message.
git reset HEAD~1 to undo the commit from current branch.
- (optional) continue working on the feature.
Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master which is another WD sharing the same .git
git reflog to find the bugfix I've just made.
git cherry-pick SHA1 of the commit.
Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project which is the main WD I'm working on.
git rebase master to get the bugfixes.
This way I can keep working on the feature uninterrupted and not have to worry about git stash-ing anything or having to clean my WD before a git checkout (and then having the check the feature branch backout again.) and still have all my bugfixes goes to master instead of hidden in my feature branch.
IMO git stash and git checkout is a real PIA when you are in the middle of working on some big feature.