Accidentally working on a wrong branch in GIT

You started working on a new feature. You pull a fresh master branch.

git checkout master
git pull origin master

Run the test suite, look around the updated repo. Head out for coffee. Come back, started working on the new feature. Edited a bunch of stuff, then: Whoops! You wanted to be on the new_feature branch.

So now you want these changes, which you have not yet committed to master, to be on new_feature.

1: If you don’t have a new_feature branch yet, the method is super easy:

$ git checkout -b new_feature

This creates a new new_feature branch starting from wherever you are now. Now you can commit and the new stuff is all on new_feature.

2: You do have a new_feature. First thing you do is see if git will let you switch without doing anything:

$ git checkout new_feature

If this succeeds, awesome! You just need to commit. However, if there is an error: Your local changes to the following files would be overwritten ..., the easiest to way to solve this is to use git stash.

This command commits your code, however it is not on any branch but it still exists on the repository.

git stash

Now you can go to the branch you want to commit the changes to.

git checkout new_feature

This commands puts your stashed changes on the current branch your are on.

git stash apply

Next step is to delete the references to the stash. You can do this by executing this command:

git stash drop

You can also use git stash pop which is a shorthand for the apply and drop command.