Moving unstaged changes between branches in git using the stash commandFebruary 19, 2017
I have been using Git for a while now, but we only recently started incorporating it more in our teams work. Using it in a collaborative manner definitely presents new challenges. But ever since I started working with version control I have been a huge fan of it, although I think I have only used a tiny percentage of what it offers. In the beginning I was just adding up commits in a straight line. It was hard enough but I already felt a great benefit: it drastically decreases the cognitive load of changing things. When re-entering a codebase, I can quickly head over to GitHub and browse the latest commits to see where I am at. I also learned how to jump back and forth in the history of a repository, to inspect the complete codebase at any given time. I found great value in these features alone, but now I am starting to see the real benefits in collaboration. We are applying most changes through pull requests and that requires me to operate a lot with different branches. Usually someone will create a new branch, apply changes and make a pull request. Sometimes this gets me into a situation that I cannot seem to get out of. Recently I found a clean solution for one of these tricky situations where I would have to manually copy changes otherwise.
Problem: I make local changes to some branch. Then I realize that I am on the wrong branch and my changes were meant for another one. But my changes are not ready to be commited and merged, I do not want to add them to Git yet. So how do I copy local unstaged changes from one branch to another?
Solution: Git has something built-in that acts like a clipboard for the local state of a repository. You can save your local unstaged changes from the repo inside this clipboard, switch branches and then sort of paste the changes inside the new branch. Assuming I want move my changes to a branch called correct-branch, I run the following commands:
git stash git checkout correct-branch git stash pop
Sometimes I want to move my unstaged changes into a new branch that does not exist yet. This happens fairly often when I am quickly trying out things locally on the master branch and then want to get more serious with it. Only two additional characters are needed:
git stash git checkout -b new-branch git stash pop
This will move all the local unstaged changes into a new branch. That was my first need and use of the stash command. Reading the documentation now I realize that it is also very useful in another situation. It is described as tool for temporarily moving onto another branch without having to commit all changes on the current one 1. I will definitely start to make use of this as well!